I thought I was on the code with this but I realised that the code will output the different elements in a new array TWICE…
Is there no function to check all elements of an array for multiple arrays and compare elements? I tried .includes , if that’s the right one can someone give me a pointer on how to fix this?
Your code so far
function diffArray(arr1, arr2) {
var newArr = [];
for (let i = 0 ; i<arr1.length ; i++) {
if ( (arr1.includes(arr2[i])) === false ) {
newArr.push(arr2[i]);
console.log(newArr);
} else if ( (arr2.includes(arr1[i])) === false ) {
newArr.push(arr1[i]);
}
}
return newArr;
}
console.log(diffArray(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.
Link to the challenge:
so an if statement to check if the lengths are not equal.
if (arr1.length !=arr2.length)
hmm… what I’m thinking atm is that if either is unequal, to extend the length by the difference of what their length is
But that would lead to empty/ null elements then we have the same problem in the end ultimately when all are compared, newArr will have null elements if both arrays do not share that :S
This explanation is excellent, thank you.
This is my new attempt via converting your logic into code - it’s better than the other one but I’m still slipping somewhere. Today has been a long day so I’m sure I’ll get it tomorrow. Give pointers when you can thank you
function diffArray(arr1, arr2) {
var newArr = [];
if (arr1.length > arr2.length)
{
for (let i = 0 ; i<arr1.length ; i++) {
if ( (arr2.includes(arr1[i]) == false) && ((arr2[i] !== undefined))) {
newArr.push(arr1[i]);
}
} } else {
for (let i = 0; i<arr2.length; i++) {
if ( (arr1.includes(arr2[i]) == false) && ((arr1[i] !== undefined)) ) {
if (arr1[i] != undefined) {
newArr.push(arr2[i]);
}
}
}
}
return newArr;
}