+ 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);

23rd Feb 2019, 3:38 AM
A B
A B - avatar
8 Respuestas
+ 1
arr3 = arr1.filter((a)=>!arr2.includes(a));
23rd Feb 2019, 7:35 PM
Микола Федосєєв
Микола Федосєєв - avatar
+ 9
You can do something like this instead of doing much long. https://code.sololearn.com/WawEOohlcFay/?ref=app
23rd Feb 2019, 3:58 AM
Arushi Singhania
Arushi Singhania - avatar
+ 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
23rd Feb 2019, 4:27 AM
Calviղ
Calviղ - avatar
+ 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
23rd Feb 2019, 3:54 AM
Шащи Ранжан
Шащи Ранжан - avatar
23rd Feb 2019, 8:23 AM
ODLNT
ODLNT - avatar
+ 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.
23rd Feb 2019, 4:11 AM
Шащи Ранжан
Шащи Ранжан - avatar
0
solution array1.splice(i, 1) } } } return array1 } thank you to everybody for showing me many different ways to solve this algorithm.
23rd Feb 2019, 4:39 AM
A B
A B - avatar
0
কি ভাবে আমি আমার পেইচ-বুক ওয়াড়সটপ্স গেম ফলোয়ারদের হাত থেকে বাঁচবো
23rd Feb 2019, 12:31 PM
Sohel Rana