user10392610
user10392610

Reputation:

How to find a specific array in an array?

I have got this code:

var test = [[1,1], "b","a"];
    function findArray(element) {
        return element == [1,1];
    }
    console.log(test.find(findArray));

It returns:

undefined

What should I do to find the [1,1] array inside of the test array? (I do not want to loop through it though)

Upvotes: 2

Views: 476

Answers (2)

Code Maniac
Code Maniac

Reputation: 37755

You can't compare two objects with === or == since they are references and will evaluate to true only if they are pointing to the same address.

You need to match each element from first array with respective index in second array to check for similarity, you can use every.

var test = [ [1, 1], "b", "a"];

function findArray(element) {
  if(Array.isArray(element)){
    let arrayToMatchWith = [1,1]
    if(element.length === arrayToMatchWith.length){
      return element.every((v,i)=> v === arrayToMatchWith[i])
    }
  }
  return false
}
console.log(test.find(findArray));
console.log([[1,2]].find(findArray));
console.log([[1,1,1]].find(findArray));
console.log([[1]].find(findArray));


Could I pass the searched array as an argument?

Yes you can. Here I am using a curried function:

var test = [[1, 1], "b", "a"];

let curried = (arr) => (element) => {
  if (Array.isArray(element)) {
    if (element.length === arr.length) {
      return element.every((v, i) => v === arr[i])
    }
  }
  return false
}

let curried1 = curried([1,1])
console.log(test.find(curried1));
let curried2 = curried([1,2,2])
console.log([[1, 2]].find(curried2));
let curried3 = curried([1,1,1])
console.log([[1, 1, 1]].find(curried3));
let curried4 = curried([1])
console.log([[1]].find(curried4));

Upvotes: 6

Charlie
Charlie

Reputation: 23778

The array literal in your comparison is a different object than the array inside your original array. If you derive a comparable entity from each array, you can check for that inside the find method. One way to do it is by calling the toString method.

This is only required if you really don't want to loop through the array for comparison.

var test = [[1,1], "b","a"];

 function findArray(element) {
    
   if (element.constructor === Array)
      return element.toString() == [1,1].toString();
 }
    
 console.log(test.find(findArray));

Upvotes: 0

Related Questions