Eliminate duplicate objects from arrays of objects by a specific key name

Here are some arrays of objects I am working with:

var arr = [
  {name: 'john', last: 'smith'},
  {name: 'jane', last: 'doe'},
  {name: 'johnny', last: 'appleseed'},
  {name: 'johnson', last: 'smith'},
  {name: 'jane', last: 'smith'}
]

My goal is to eliminate duplicates based on the key name. The expected output should be:

var arr = [
  {name: 'john', last: 'smith'},
  {name: 'jane', last: 'doe'},
  {name: 'johnny', last: 'appleseed'},
  {name: 'johnson', last: 'smith'}
]

I attempted to achieve this using the following method:

function _unique(arr) {
  let uniqueArr = [];

  for (var i = 0; i < arr.length; i++) {
    for(var j=i+1; j<arr.length; j++) {
      if(arr[i].name.indexOf(arr[j].name) == -1) {
        uniqueArr.push(arr[j])
      }
    }
  }

  return uniqueArr;
}

console.log(_unique(arr))

Unfortunately, the program did not produce the desired result.

Any help or guidance would be greatly appreciated!

Answer №1

Aggregate data into a collection organized by the

name</coide> attribute, only setting the property if it is not already occupied, then retrieve the values of that collection:</p>

<p><div>
<div>
<pre class="lang-js"><code>var list = [
  {name: 'john', surname: 'smith'},
  {name: 'john', surname: 'doe'},
  {name: 'alice', surname: 'jones'},
  {name: 'bob', surname: 'brown'},
  {name: 'bob', surname: 'white'},
  {name: 'tom', surname: 'harris'},
  {name: 'tom', surname: 'clark'},
];
const result = Object.values(list.reduce((accumulator, item) => {
  if (!accumulator[item.name]) accumulator[item.name] = item;
  return accumulator;
}, {}));
console.log(result);

Answer №2

const users = [
  {firstName: 'John', lastName: 'Doe'},
  {firstName: 'Jane', lastName: 'Smith'},
  {firstName: 'Alice', lastName: 'Johnson'},
  {firstName: 'Bob', lastName: 'Brown'},
  {firstName: 'Bob', lastName: 'White'},
  {firstName: 'Charlie', lastName: 'Davis'},
  {firstName: 'Charlie', lastName: 'Williams'},
  {firstName: 'David', lastName: 'Wilson'}
];

const uniqueUsers = users
  .sort((a, b) => a.firstName - b.firstName)
  .reduce((acc, curr) => {
    let length = acc.length;
    if(length === 0 || acc[length - 1].firstName !== curr.firstName) {
      acc.push(curr);
    }
    return acc;
  }, []);

console.log(uniqueUsers);

Answer №3

Just made a slight modification to your solution:

function _unique(arr) {
  let uniqueArr = [];

  for (var i = 0; i < arr.length; i++) {
    let existed = false
    for (var j = 0; j < uniqueArr.length; j++) 
      if (arr[i].name === uniqueArr[j].name) {
        existed = true
        break
      }

    if (existed) continue
    uniqueArr.push(arr[i])
  }

  return uniqueArr;
}

Answer №4

To obtain the final array, you can utilize both .reduce() and Object.values():

let data = [
  {name: 'rajendra', last: 'arora'},    {name: 'rajendra', last: 'arora2'},
  {name: 'rajendra1', last: 'arora22'}, {name: 'rajendra2', last: 'arora233'},
  {name: 'rajendra2', last: 'arora23'}, {name: 'rajendra3', last: 'arora3'},
  {name: 'rajendra3', last: 'arora3'},  {name: 'rajendr3', last: 'arora3'}
];

let result = Object.values(data.reduce((r, c) => (r[c.name] = r[c.name] || c, r), {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

When subscribed to, the BehaviorSubject will return the object twice

When working with a bank API for payments, the response expected by the banks is that Ban Pay JavaScript will perform an HTTP redirect in the top frame to a completeUrl. The question arises - what should be the completeUrl that I need to provide to the ban ...

Adjust transparency according to the information extracted from the AnalyserNode

Currently, I am exploring ways to animate text opacity based on the volume of an audio file. While browsing online, I came across this specific codepen example, which showcases a similar concept. However, as I am relatively new to JavaScript, I find it ch ...

Generating an error during mongoose callback

Currently, I am in the process of developing a Node.js + Express application. The database I am working with is Mongo, and I have integrated Mongoose to establish a connection with this database. In my code, I am attempting to handle exceptions within a M ...

Having issues with reading files in PHP using AJAX? Explore alternative methods for downloading files seamlessly

I need to store a value in a txt file and allow the user to download it. Currently, the value is successfully written to the txt file, but the readfile function does not execute, preventing the download from starting. The PHP code is on the same page as ...

How do I adjust brightness and contrast filters on a base64 URL?

When presented with an image in base64 format like this: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDAAwfqNRk/rjcYX+PxrV/wtWqwJSTlboMgAAAABJRU5ErkJggg== What is the most efficient method to programmatically alter a filter (such as brightness or cont ...

Encountering an "Unexpected token" error during Woocommerce checkout when using pretty links

I currently have a Wordpress e-commerce site (using Woocommerce) set up on my VPS (running Caddy and NGinx). Initially, I had "index.php" in my URI, so I added these lines to my configuration file to rewrite the URI and enable pretty links. Success! It&a ...

"Encountering an error stating "breakpoint set but not yet bound" while debugging a node.js application

After following the instructions in this link to configure Visual Studio code for debugging nodejs and chrome(vuejs) applications, I encountered an error message saying "Failed to exec debug script" when attempting to debug "Meteor All" in Visual Studio co ...

Inject a DOM event into a personalized form validator within an Angular application

I'm currently working on validating a form using the reactive approach. I've implemented a file input to allow users to upload files, with custom validation conditions in place. However, I'm encountering an issue where the validator only rec ...

After a successful login, learn how to implement a bottom tab menu in React Native

I'm diving into the world of react-native and finding myself a bit lost when it comes to routing and navigation. I have 4 screens - Login, Register, Home, and Links. The Register and Login screens are all set up, with the ability to navigate back usin ...

Utilize the appendTo() function and make a switch to dynamically insert content stored in variables into a specified

I am working on developing a page with a central content div, where users have the ability to choose various options that will introduce different additional content. This added content will then present more opportunities for adding new elements, ultimate ...

Efficiently altering values with Python Numpy

Currently in my program, I am generating a numpy array filled with zeros and then iterating over each element to replace it with the desired value. Is there a more efficient approach for accomplishing this task? Here is an example of what I am currently d ...

Errors with pointer events occurring within nested iframes on Chromium 78

At first glance, it seems like a bug specific to Chromium. I have already reported this issue in a bug report. Since progress is slow on that front, I am posting a question here primarily to see if anyone else has encountered similar or related issues and ...

Solving runtime JavaScript attribute issues by deciphering TypeScript compiler notifications

Here is a code snippet I am currently working with: <div class="authentication-validation-message-container"> <ng-container *ngIf="email.invalid && (email.dirty || email.touched)"> <div class="validation-error-message" *ngIf=" ...

Issue with padding in Material UI button component not being applied as expected

I am struggling with applying padding and styles to my Material UI component. Take a look at the code snippet below: import "./css/Landing.css"; import { Button } from "@mui/material"; function Landing() { return ( <div class ...

Having trouble sending data through a jQuery AJAX request?

When I make a post request using jQuery AJAX to an ActionResult method, I encounter the following issue: $("#itemTextbox, #itemTextboxNew, #quantity1Textbox").on("keydown", function (e) { if ((e.keyCode == 120){ var GetReportLast5SellAndBuyURL="/Trd/Se ...

What is the best way to separate axios functions and components in Vue3?

In my opinion, it's more efficient to separate the axios commands from the vue components. This is how I structured my directories: src api - products.js components - Products.vue products.js import axios from 'axios'; const li ...

Tips on successfully passing multiple keys and their associated HTML tag attributes in a React application

One of my links, specified with an a-tag, appears in this manner: <a href={ item.htmlReportUrl } target="_blank" rel="noopener noreferrer"> {item.htmlReportText}</a> The values for the href and the linktext are sourced from the following: ro ...

Encountering a script error when upgrading to rc4 in Angular 2

After attempting to update my Angular 2 version to 2.0.0.rc.4, I encountered a script error following npm install and npm start. Please see my package.json file below "dependencies": { "@angular/common": "2.0.0-rc.4", "@angular/core": "2.0.0-rc.4", ...

How is the height or width of the Bootstrap modal determined?

I'm having trouble utilizing Jschr's modified Bootstrap-Modal for different modal sizes. I can't seem to understand why some modals appear taller, wider, or have other specific dimensions. For more information, refer to the documentation: ...

What are some methods for utilizing the data received through this.props.history?

Whenever I need to navigate from one route to another using this.props.history.push("/"), I also want to pass along some extra data. For example: this.props.history.push('/postDetail', {data: item}). However, I am uncertain about where to define ...