Search code examples
javascriptlodash

Some lodash functions aren't defined


Some of the lodash function gives 'not a function error'. For example: _.minBy, _.maxBy, _.cloneDeep etc.

Other functions like _.map, _.clone etc. are working fine. I tried with lodash 4 and lodash 3.

Here is my code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.1.0/lodash.js"></script>
<script type="text/javascript">
var drinks = [
  { 'name': 'Coke', 'quantity': 2 },
  { 'name': 'Red Bull', 'quantity': 6 }
];
var currentDrinks = _.map(drinks, 'name');
console.log(currentDrinks);
// → [‘Coke’, ‘Red Bull’]
var a = [{"type":"exam","score":47.67196715489599},{"type":"quiz","score":41.55743490493954},{"type":"homework","score":70.4612811769744},{"type":"homework","score":48.60803337116214}];

const b = _.minBy(a, 'score');
console.log(b);

</script>

Here _.map works and _.minBy not working. Which version of lodash I should use to support for _.minBy and _.deepClone?


Solution

  • It works perfectly with lodash 4:

    var drinks = [
      { 'name': 'Coke', 'quantity': 2 },
      { 'name': 'Red Bull', 'quantity': 6 }
    ];
    var currentDrinks = _.map(drinks, 'name');
    console.log(currentDrinks); // → [‘Coke’, ‘Red Bull’]
    var a = [
      {"type":"exam","score":47.67196715489599},
      {"type":"quiz","score":41.55743490493954},
      {"type":"homework","score":70.4612811769744},
      {"type":"homework","score":48.60803337116214}
    ];
    const b = _.minBy(a, 'score');
    console.log(b);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>

    .minBy and .maxBy have been introduced in version 4.0.0. Just use a version higher than this.

    Edit: In the file you uploaded, you aren't specifying the whole library. You are just loading the core. (In your question you referenced however the correct file, but the wrong version.)

    Change:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.core.min.js"></script>
    

    to:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>