Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Eliminating Duplicate Objects from Arrays in JavaScript

Tech 3
const log = console.log.bind(console);

const individuals = [
  { id: 0, name: "Xiao Ming" },
  { id: 1, name: "Xiao Zhang" },
  { id: 2, name: "Xiao Li" },
  { id: 3, name: "Xiao Sun" },
  { id: 1, name: "Xiao Zhou" },
  { id: 2, name: "Xiao Chen" }
];

const seen = {};

const uniqueIndividuals = individuals.reduce((accumulator, current) => {
  if (!seen[current.id]) {
    seen[current.id] = true;
    accumulator.push(current);
  }
  return accumulator;
}, []);

log(uniqueIndividuals);
const sourceArray = [
  { id: 1, name: "Zhang San", age: 18, contactId: 1 },
  { id: 1, name: "Zhang San", age: 18, contactId: 2 },
  { id: 1, name: "Zhang San", age: 18, contactId: 3 },
  { id: 1, name: "Zhang San", age: 18, contactId: 14 },
  { id: 1, name: "Zhang San", age: 18, contactId: 3 },
  { id: 1, name: "Zhang San", age: 18, contactId: 2 },
  { id: 1, name: "Zhang San", age: 18, contactId: 1 }
];

const resultArray = [];

// jQuery approach
$.each(sourceArray, function(index, item) {
  let exists = false;
  $.each(resultArray, function(innerIndex, existingItem) {
    if (existingItem.contactId === item.contactId) {
      exists = true;
      return false; // break loop
    }
  });
  if (!exists) {
    resultArray.push(item);
  }
});
// Vanilla JavaScript approach
for (let i = 0; i < sourceArray.length; i++) {
  let found = false;
  for (let j = 0; j < resultArray.length; j++) {
    if (sourceArray[i].id === resultArray[j].id) {
      found = true;
      break;
    }
  }
  if (!found) {
    resultArray.push(sourceArray[i]);
  }
}
function findMatchingUser() {
  for (let i = 0; i < self.tableDataUser.length; i++) {
    if (self.radioUser.indexOf(self.tableDataUser[i].userId) > -1) {
      return self.tableDataUser[i];
    }
  }
  return null;
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.