I am trying to remove any duplicate from a JSON-like data list, so if there are two or more items with the same name, I just want to keep one. I am trying to solve it with this naive approach. And when I try to push the (data[i].name, data[i].age) to an empty array newData, the end result is just an empty array. But, if the array already had some value, it works. Here's the console:
[] //this result is with empty array
(9) [1, "player1", 10, "player2", 30] //this result is with newData.push(1);
Here the code
function someFunction(data) {
const newData = [];
newData.push(1);
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < newData.length; j++) {
if (i !== j) {
if (!newData.includes(data[i].name)) {
newData.push(data[i].name, data[i].age);
}
}
}
}
return newData;
}
lets say I have a data list like this:
const data = [
{
name: "player1",
score: 10
},
{
name: "player2",
score: 30
},
{
name: "player1",
score: 10
},
]
Can someone help to explain? And I came up with this idea on my own, I know I can use something like array.reduce() or a hashmap, but I really want to know if I can do it this way. Also, is there any way that I can push (data[i].name, data[i].age) to the array as one element? I think I am adding two at one iteration. Thank you!