Ok, so I want to return the elements that are present in both provided arrays having the same index location.
exe1 = [A,B,C,D,N]
exe2 = [B,D,C,A,T]
it should return only C
I've tried looping them by nested loops but doesn't work, here is what I've tried:
let testing = []
for (let i = 0; i < exe1.length; i ){
for(let j = 0; j < exe2.length; j ){
if(exe1[i] === exe2[j]){
testing.push(exe1[i])
}
}
};
return testing;
mind the names of the arrays, please
CodePudding user response:
You can use a simple filter to only include values in exe1
that have the same value at the same index of exe2
.
const exe1 = ['A','B','C','D','N'];
const exe2 = ['B','D','C','A','T'];
const testing = exe1.filter((val, i) => val === exe2[i]);
console.log(testing)
CodePudding user response:
If you want to create a function that can do this and the datatypes are primitives you can do something like this. Just a loop that goes through each index, checks both arrays, and returns the value that is the same.
const exe1 = ["A","B","C","D","N"];
const exe2 = ["B","D","C","A","T"];
function getElementsThatAreTheSame(arr1, arr2) {
const minLength = Math.min(arr1.length, arr2.length);
const sameArray = [];
for (let i = 0; i < minLength; i ) {
const item1 = arr1[i];
const item2 = arr2[i];
if (item1 == item2) sameArray.push(item1);
}
return sameArray;
}
const sameItems = getElementsThatAreTheSame(exe1, exe2);
console.log(sameItems)
However you could also use the filter method to accomplish this pretty easily as follows:
const exe1 = ["A","B","C","D","N"];
const exe2 = ["B","D","C","A","T"];
const sameArr = exe1.filter((e, i) => exe2[i] == e);
console.log(sameArr);
the filter method will take a function as an argument to which is passed the element in the array and the index of that element. We can just check the second array at that index and make sure it is the same element.
Both these approaches will not verify if it is two objects which have the same content, but are different objects. i.e. {foo: "bar"} !== {foo: "bar"}