Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
Using for loop to add elements to an empty array

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!

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!