Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript check if an array contains same element at the same index

I have two arrays-

var A =  ["a", "b", "c", "a", "b"];
var B = [["a", "b", "c", "a", "b"], ["c", "a", "b", "a", "b"]];
R = [5, 2];

Need a result R = [5, 2] as in first element of B have same element as A and second element have only 2 elements similar at same index.

I tried an approach with map but its failing.

var o =  ["a", "b", "c", "a", "b"];
var rS = [["a", "b", "c", "a", "b"], ["c", "a", "b", "a", "b"]];
var result = Array(rS.length).fill(0);

rS.map((e1,i1,a1)=>{
    e1.map((e2,i2,a2)=>{
        rS[i1][i2] === o[i1] ? result[i1]+=1 : result[i1]+=0;
    })
})
like image 998
jinks Avatar asked Jan 12 '20 09:01

jinks


People also ask

How do you check if every element in an array is the same JavaScript?

Javascript Useful Snippets — allEqual() In order to check whether every value of your records/array is equal to each other or not, you can use this function. allEqual() function returns true if the all records of a collection are equal and false otherwise.

How do you check if an array contains the same value?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.

How do you check if two arrays contain common items?

Use the inbuilt ES6 function some() to iterate through each and every element of first array and to test the array. Use the inbuilt function includes() with second array to check if element exist in the first array or not. If element exist then return true else return false.

How do you check if an array contains a specific value in JavaScript?

JavaScript Array includes()The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found. The includes() method is case sensitive.


2 Answers

You could map b with the result of the count if the nested array item who match.

var a =  ["a", "b", "c", "a", "b"],
    b = [["a", "b", "c", "a", "b"], ["c", "a", "b", "a", "b"]],
    result = b.map(values =>
        values.reduce((count, value, index) => count + (value === a[index]), 0)
    );

console.log(result);
like image 197
Nina Scholz Avatar answered Oct 06 '22 01:10

Nina Scholz


I hope this works:

var result = A.filter(e => B.indexOf(e) !== -1).length === B.length
console.log(result);
like image 23
Mahdi Avatar answered Oct 06 '22 00:10

Mahdi