+ 3
How to push and array into another array
I'm trying to create a for loop that will loop through both arrays and then push the elements that array1 has but not array 2. So far this is what I have var array1 = [{name: "Whitney"}, {name: "Cher"}, {name: "Tina"},{name: "Celine"}, {name: "Madonna"}, {name: "Janet"}]; var array2 = [{name: "Tina"}, {name: "Madonna"}]; function createNewArray() { for (var i = 0; i < array1.length; i++) { for (var j = 0; j < array2.length; j++) { if (array1[i] == array2[j]) { } } } } var array3 = createNewArray(); console.log(array3);
8 Respostas
+ 1
arr3 = arr1.filter((a)=>!arr2.includes(a));
+ 9
You can do something like this instead of doing much long.
https://code.sololearn.com/WawEOohlcFay/?ref=app
+ 5
Here you go:
var array1 = [{name: "Whitney"}, {name: "Cher"}, {name: "Tina"},{name: "Celine"}, {name: "Madonna"}, {name: "Janet"}];
var array2 = [{name: "Tina"}, {name: "Madonna"}];
function createNewArray() {
var arr = [];
for (var i = 0; i < array1.length; i++) {
var j;
for (var j = 0; j < array2.length; j++) {
if (array1[i].name === array2[j].name) break;
}
if(j===array2.length) arr.push(array1[i]);
}
return arr;
}
array3 = createNewArray();
console.log("array3 = " + JSON.stringify(array3));
https://code.sololearn.com/Wvrx32Ax0AkD/#js
+ 2
You can't compare two objects, in this case, dictionaries, directly.
Instead of comparing array1[i] and array2[i], compare array1[i].name and array2[i].name
+ 2
One more alternative.
https://code.sololearn.com/W7a5TI3BE5RT/#js
+ 1
Jay Matthews
a=[1,2,3,4]
b=[4,5,6,7]
console.log(a.concat(b))
// 1,2,3,4,4,5,6,7
But that's not the goal.
0
solution
array1.splice(i, 1)
}
}
}
return array1
}
thank you to everybody for showing me many different ways to solve this algorithm.
0
কি ভাবে আমি আমার পেইচ-বুক ওয়াড়সটপ্স গেম ফলোয়ারদের হাত থেকে বাঁচবো