I have a use case wherein I have to compare two elements of an array and display the similar elements along with the index. Suppose, I have two arrays say,
var array1 = ["One", "Two", "Three"];
var array2 = ["Four", "One", "Five"];
I want the output to be as follows:
array1
One - 1
array2
One - 2
I have written the below code snippet to find out the similar elements in both the arrays but unable to proceed on the above.
const filteredArray = array1.filter(value => array2.includes(value));
Please help.
Array#reduce, iterate over array1 while updating the resulting list of common items having the value, index in array1, and index in array2Array#findIndex, get the index of the current value in array2, if it exists, push a new item to the resulting array.const
array1 = ["One", "Two", "Three"],
array2 = ["Four", "One", "Five"];
const filteredArray = array1.reduce((commonItems, value, index1) => {
const index2 = array2.findIndex(e => e === value);
if(index2 >= 0) {
commonItems.push({ value, index1, index2 });
}
return commonItems;
}, []);
console.log(filteredArray);
You can do it in this way & store it in an object
var array1 = ["One", "Two", "Three"];
var array2 = ["Four", "One", "Five"];
let obj={ array1:[],array2:[] }
array1.filter((value,i) => {
if(array2.indexOf(value) !== -1){
console.log('value',value, array2.indexOf(value))
obj["array1"].push(`value - ${i + 1}`)
obj["array2"].push(`value - ${array2.indexOf(value) + 1}`)
}
});
console.log(obj)
Output
{ array1: [ 'value - 1' ], array2: [ 'value - 2' ] }
Clarification : How for array2 it should be One - 2 ? As One is in 0th index in array1
As per my understanding, You can simply achieve this by using Array.forEach() along with the Array.indexOf() method.
Live Demo :
var array1 = ["One", "Two", "Three"];
var array2 = ["Four", "One", "Five"];
array1.forEach(item => {
if (array2.indexOf(item) !== -1) {
console.log(item, array2.indexOf(item));
}
});
array2.forEach(item => {
if (array1.indexOf(item) !== -1) {
console.log(item, array1.indexOf(item));
}
});