Home > OS >  array method to check if index value between two arrays exists in JS
array method to check if index value between two arrays exists in JS

Time:12-04

I want to compare 2 arrays and check if the value of 3 given indexes is common between the 2 arrays. i.e.:

arr1 = [1,2,1,0,0,0,2,2,2]
arr2 = [0,0,0,0,0,0,2,2,2]

or

arr1 = [1,2,3,0,1,2,4,2,1]
arr2 = [1,0,0,0,1,0,0,0,1]

1st example here last 3 indexes are common. 2nd example here index 0,4,8 are common.

is there any method that can take the 2 arrays and return true if indexes are matching?

CodePudding user response:

It's very simple

const equal = (a1, a2, ...indexes) => indexes.every(i => a1[i] === a2[i]);

What i'm doing here is declaring a function that takes the first array as the first argument and the second array as the second parameters, now the third argument is basically grouping all the remaining parameters.

You would call this function like:

equal([0, 2, 4, 6], [0, 1, 3, 6], 0, 3);

And this will return true

CodePudding user response:

Something like this:

const arr1 = [1,2,3,0,1,2,4,2,1]
const arr2 = [1,0,0,0,1,0,0,0,1]

const indexes = arr1.reduce((accumulator, current, index) => {
  if (arr2[index] === current) {
    accumulator.push(index)
  }
  return accumulator
}, [])

console.log(indexes)

// Outputs : [0,3,4,8]
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related