0

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?

2
  • There is no inbuilt method. Create a javascript function that loos through the array and check value at each indices. Commented Dec 3, 2021 at 7:39
  • If you want to return true/false based on match result then, try like const data = arr1.map((item, i) => item > 0 && arr2[i] === item ? true : false ); Eg: codepen.io/Maniraj_Murugan/pen/BawNvbX Commented Dec 3, 2021 at 8:02

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.