Eliminate duplicate elements based on a property in a JavaScript array

Looking to filter duplicates from a list of objects:

   [{name: "bob", age: "14"}, {name: "bob", age: "16"}, {name: "sue", age: "21"}]

I want to remove objects with duplicate 'name' properties, resulting in:

 [{name: "bob", age: "14"}, {name: "sue", age: "21"}]

While there are solutions for array duplicate removal, none address removing duplicates based on a specific property without considering other fields.

Answer №1

Traverse through the array, storing all name values in a hash and excluding objects with duplicate name values:

filterBy = function(ary, prop) {
  var seen = {};
  return ary.filter(function(item) {
    var key = item[prop];
    if(seen[key] === 1)
      return false;
    seen[key] = 1;
    return true;
  });
}

// 
a = [{name: "bob", age: "14"}, {name: "bob", age: "16"}, {name: "sue", age: "21"}]

b = filterBy(a, 'name');

console.log(b);

ES6 version:

filterBy = function(ary, prop) {
  var seen = new Set();
  return ary.filter(item => !seen.has(item[prop]) && seen.add(item[prop]));
}

a = [{name: "bob", age: "14"}, {name: "bob", age: "16"}, {name: "sue", age: "21"}]

b = filterBy(a, 'name');

console.log(b);

Answer №2

To achieve this, you can utilize 2 for loops. Simply maintain a result array and every time you add to it, verify if the name attributes match.

function findDuplicates(){
  var array= [{name: "john", age: "25"}, {name: "john", age: "30"}, {name: "lily", age: "27"}];

  var result=[];
  for(i in array){
    var found=false;
    for(j in result){
      if(result[j].name.localeCompare(array[i].name)==0){
        found=true;
      }
    }
    if(!found){
      result.push(array[i]);
    }
  }
  console.log(result);
}

Answer №3

To achieve this, you can utilize the forEach method along with the thisArg parameter.

var data = [{name: "alice", age: "20"}, {name: "alice", age: "22"}, {name: "john", age: "25"}];
var result = [];

data.forEach(function(person) {
  if (!this[person.name]) {
    this[person.name] = person;
    result.push(this[person.name]);
  }
}, {});

console.log(result)

Alternatively, you can also use forEach in combination with map().

var data = [{name: "alice", age: "20"}, {name: "alice", age: "22"}, {name: "john", age: "25"}];
var result =[];

data.forEach(function(person) {
  if(result.map(item => {return item.name}).indexOf(person.name) == -1 ) result.push(person);
});

console.log(result)

Answer №4

To efficiently filter out duplicate entries of the same name in an array, you can utilize the Array#filter method along with a this object for marking.

var array = [{ name: "bob", age: "14" }, { name: "bob", age: "16" }, { name: "sue", age: "21" }],
    filtered = array.filter(function (a) {
        if (!this[a.name]) {
            this[a.name] = true;
            return true;
        }
    }, Object.create(null));

console.log(filtered);

Answer №5

In the question regarding simple comparison, there are a number of great responses provided. However, if you are looking to implement a customized comparison function that can handle object values or utilize regular expressions, then consider the code snippet below.

var dedupwhen = function(fn, list){
    if(list[0] === undefined){
        return [];
    }
    // Join the first item to the remainder that has had the first
    // item filtered out (according to fn) and then been
    // deduplicated itself.
    return [list[0]].concat(dedupwhen(fn, list.slice(1).filter(function(item){
        return !fn(list[0], item);
    })));
};

var similarname = function(x,y){
    return RegExp('^' + x.name + '$', 'i').test(y.name);
};

var list = [
    {name: 'Sue', age: 44},
    {name: 'Bob', age: "14"},
    {name: 'bob', age: "16"},
    {name: 'sue', age: "21"}
];
console.log(dedupwhen(similarname, list));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What method can be used to incorporate expressions into Handlebars partials when dealing with parameters?

Is it possible to include expressions in partials parameters? I am trying to achieve something similar to this: {{> myPartial greeting=(i18n.greeting + "my text") }} ...

Create a function that takes an array as input and retrieves the element in the array that corresponds to the specified question

To solve this problem, I'm tasked with creating a function called findAnswers(answers, questions). The function should return the item in the array that corresponds to the given question. If none of the student's answers match the question, the f ...

Instructions on dynamically positioning a collection of div elements at the center of a webpage container

I am looking to create a set of divs that are centered on the page and adjust in size according to the length of the username. .Container1 { display: table; width: 100%; padding:0; margin:0; -webkit-box-sizing: border-box; -moz-box-sizing: bor ...

Feeling trapped by the endless stream of AJAX calls

As I was working on building a scheduler with jQuery and AJAX, I encountered a problem with multiple AJAX requests. Although most of the time everything works fine and returns the correct values, occasionally, out of more than 50 requests, I come across so ...

Tips on converting Django model into desired format for Bootstrap-tables plugin integration

I want to integrate the bootstrap-table plugin with server-side functionality using Django Rest Framework to populate the data on the table. However, I keep getting the message "No matching records found". After some investigation, I discovered that a spec ...

Encountered error message: "Cannot assign argument of type '() => () => boolean' to parameter of type 'EffectCallback'"

I recently started working with TypeScript. I encountered an issue when attempting to utilize useEffect in TypeScript within a React context, Error: Argument of type '() => () => boolean' is not assignable to parameter of type 'Effec ...

Ways to alter the typography style if the text exceeds a certain length

I need some assistance with using Material UI in my ReactJs project with TypeScript. I am trying to decrease the font size of typography when the text exceeds 3 lines. Here is a snippet of my code: const checkFontSize =() => { if(text.leng ...

Scheduled tasks on Google Cloud Platform's App Engine are failing to run over the weekend

I am facing an issue with running a cron job in my node/express application using the node-cron library. The application is hosted on Google Cloud App Engine. My aim is to automate sending emails every day at 9 AM, but the cron seems to only work from Mon ...

Clickable elements are not functioning on dynamically generated divs

In the process of developing an application using Angular, I encountered a scenario where I needed to fetch and display data from a web service. The challenge was in dynamically creating div elements with the retrieved data: for(var i = 0 ; i < data.Ou ...

Differences Between Data Captured from Form Submissions and Data Obtained Through Ajax

When attempting to incorporate reCAPTCHA into my MVC site, I encountered an issue where it would not validate unless submitted from a form. Here is the current implementation: @using(Html.BeginForm("VerifyCaptcha", "Signup") ) { @ReCaptch ...

Attempting to retrieve user information from Blockstack on a web browser

Currently developing a web application integrating Blockstack and encountering challenges with Javascript implementation and understanding how to effectively use Blockstack in the browser. My issue arises when retrieving the Blockstack user's ID or u ...

Aligning a navigation bar with a hamburger menu in the center

I recently implemented a hamburger menu with some cool animations into my site for mobile devices. Now, I am facing the challenge of centering the menu on desktop screens and it's proving to be tricky. The positioning is off, and traditional methods l ...

How can I utilize the context menu feature within a Material React Table row?

I am looking to implement a context menu for each row of the MUI Table, but I haven't found a suitable example. Is there native support for row-level context menus in the MUI Table, or is it possible to add this functionality per row? For reference, ...

Webhost sending information to Windows sidebar gadget

Is there a way to showcase a list of information from a web host on a Windows sidebar gadget without using iframes? I've heard about using JavaScript AJAX (XmlHttpRequest) for this purpose, along with a refreshing function. Can anyone provide some gui ...

Could not locate module: The package path ./react is not exported from the package in E:NextAppportfolio_website-mainportfolio_website-main ode_modules ext-auth

I am encountering an issue while trying to import SessionProvider from Next-Auth. The error message that is being displayed is: "Module not found: Package path ./react is not exported from package E:\NextApp\portfolio_website-main\port ...

Selecting a Child Component in Vue.js: A Guide to Specifying the Correct Component

Within my application, I have a variety of components that are either generic or specific to certain brands. For example, I have two brand-specific components named Product_brand_A.vue and Product_brand_B.vue, both of which I want to display in a list form ...

Leveraging an external TypeScript library in a TypeScript internal module

Imagine you find yourself in a situation where you need to utilize a typescript/node library within an internal module that is spanned across multiple .ts files. ApiRepositoryHelper.ts import * as requestPromise from "request-promise"; module ApiHelp ...

Angular, PHP, and MySQL working together to establish database connectivity

Greetings! I am facing some challenges with a small project involving mySQL and PHP for the first time. My main focus right now is on establishing connectivity. Despite following various tutorials, I have been unable to connect to the database and keep enc ...

Incorporating Redux into Angular 2 with SystemJS loading technique

I have been delving into learning Angular 2 and I am keen on integrating Redux into my project. Currently, I have set up my project using angular-cli on rc2 release. This is my systemjs configuration: /************************************************** ...

Updating the information displayed in one section by selecting a button on the Google Maps infowindow located in a separate section

My webpage is divided into multiple divisions. One division contains a map using the Google Maps API with markers. When I click on a marker, an info window opens up. Now, I am attempting to place a button inside that info window which, when clicked, will ...