Jin DO
Jin DO

Reputation: 59

lodash find array in array returns undefined

I have 2 arrays

const arr1 = [[1,2],[3,4],[5,6]];
const arr2 = [1,2,3,4,5];

I want to get the specific element in these array to log
There are 2 cases:
1/

console.log(_.find(arr1,0,1));
console.log(_.find(arr2,0,1));

it return undefined with arr2
2/

console.log(_.find(arr1[1],0,1));

This one also returns undefined.
Can anyone tell me what I am missing here ?

EDIT
For console.log(_.find(arr1,0,1)); I and @Mr.7 got 2 different results: the result I have on Chrome console is [3,4] but on jsfiddle is [1,2] which is the same as Mr.7. And I have noticed some thing strange in this _.find
Here is my code :

import _ from 'lodash';

const arr1 = [[1,2],[3,4],[5,6]];
const arr2 = [1,2,3,4,5];
const arr3 = [[0,2],[3,4],[5,6]];

console.log(_.find(arr1,1,1));//[3,4]
console.log(_.find(arr1,0,1));//[3,4]
console.log(_.find(arr2,2));//undefined
console.log(_.find(arr1,0));//[1,2]

console.log(_.find(arr3,0));//[3,4]
console.log(_.find(arr1,1));//[1,2]

Upvotes: 3

Views: 2066

Answers (1)

Pineda
Pineda

Reputation: 7593

You are passing in a Number as a 2nd argument when:

Lodash _.find() expects a function as its 2nd argument that is invoked per iteration.

The function passed in as a 2nd argument accepts three parameters:

  • value - current value being iterated on

  • index|key - the current index value for the array or key for a collection

  • collection - a reference to the collection being iterated over

You are passing in the value of indexes where a function is required.

If you wanted to get the 2nd element in arr1 you don't need lodash, but can access direct using bracket notation and the index number:

arr1[1]

If you insist on using lodash, you can the 2nd element of arr1 as follows (although why you'd prefer this approach is questionable):

_.find(
     arr1,               // array to iterate over
     function(value, index, collection){   // the FUNCTION to use over each iteration
       if(index ===1)console.log(value)    // is the element at position 2?
     }, 
     1                   // the index of the array to start iterating from
   );                    // since you are looking for the element at position 2,
                         // this value 1 is passed, although with this set-up
                         // omitting won't break it but it would just be less efficient

Upvotes: 5

Related Questions