0

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!

  • _"I just want to keep one"_... which one? – Phil Jan 31 '22 at 23:17
  • 1
    `j < newData.length` If `newData == []` then `newData.length === 0` and it never goes into the `for`. – Heretic Monkey Jan 31 '22 at 23:20
  • `newData.push([data[i].name, data[i].age])` but the `includes` check will need to be updated to use `some`. You're better off just doing `newData = data.map(el => [el.name, el.age])`, or `newData = data.map(el => Object.values(el))` – Heretic Monkey Jan 31 '22 at 23:24
  • @Phil I would say the first one, so, if 'player1' already exist in the newData array, then I don't want to add it to the newData array again. – Matthew Chan Feb 01 '22 at 01:47
  • @HereticMonkey OMG, I don't even know how I missed that. Now, I am thinking that I can add the first object from the data list at the beginning when I create the newData array – Matthew Chan Feb 01 '22 at 01:50

0 Answers0