Finding the initial occurrence of duplicates within an array of objects using JavaScript

I am working with a data structure retrieved from an API, and it looks like this:

[
  {
    id: '10000844',
    text_id: '10000844-01',
  },
  {
    id: '10000844',
    text_id: '10000844-02',
  },
  {
    id: '12000844',
    text_id: '12000844-03',
  },
  {
    id: '12000844',
    text_id: '12000844-07',
  },
  {
    id: '12000814',
    text_id: '12000844-07',
  },
 {
    id: '12002812',
    text_id: '12000844-07',
  },
   {
    id: '12000814',
    text_id: '12000844-08',
  },
]

After cleaning up the code, I want the result to only contain the first occurrence of each unique ID:

[
      {
        id: '10000844',
        text_id: '10000844-01',
      },
      {
        id: '12000844',
        text_id: '12000844-03',
      },
      {
        id: '12000814',
        text_id: '12000844-07',
      },
     {
        id: '12002812',
        text_id: '12000844-07',
      },
    ]

However, my current code is only returning the last duplicate found in a unique array. Here is the snippet:

let uniqueArray = [...new Map(data.map(item =>
    [item.id, item])).values()];

Answer №1

You have the option to utilize Object.values() and reduce() in the following way:

const data = [
  {
    id: '10000844',
    text_id: '10000844-01',
  },
  {
    id: '10000844',
    text_id: '10000844-02',
  },
  {
    id: '12000844',
    text_id: '12000844-03',
  },
  {
    id: '12000844',
    text_id: '12000844-07',
  },
  {
    id: '12000814',
    text_id: '12000844-07',
  },
  {
    id: '12002812',
    text_id: '12000844-07',
  },
   {
    id: '12000814',
    text_id: '12000844-08',
  },
]

const result = Object.values(
  data.reduce((res, {id, text_id}) => {
    res[id] ??= {id, text_id}
    return res
  }, {})
)
console.log(result)

Enhancement using ??= source

The logical nullish assignment (x ??= y) operator will solely assign

if x is nullish (null or undefined)
.

Answer №2

Follow these steps to achieve it:

const array = [
  {
    id: '10000844',
    text_id: '10000844-01',
  },
  {
    id: '12000814',
    text_id: '12000844-08',
  },
  {
    id: '12002812',
    text_id: '12000844-07',
  },
];
const uniqueValues = [];
const memory = new Set();
for(let index = 0; index < array.length; ++index){
  if(!memory.has(array[index].id)){
    uniqueValues.push(array[index]);
    memory.add(array[index].id);
  }
}

console.log(uniqueValues);

Answer №3

Approach:

To filter out unique objects based on the id field, iterate through the data array and only add items to the result array if their id is not already present in it.

Solution:

const data = [{
          id: '10000844',
          text_id: '10000844-01',
        },
        {
          id: '10000844',
          text_id: '10000844-02',
        },
        {
          id: '12000844',
          text_id: '12000844-03',
        },
        {
          id: '12000844',
          text_id: '12000844-07',
        },
        {
          id: '12000814',
          text_id: '12000844-07',
        },
        {
          id: '12002812',
          text_id: '12000844-07',
        },
        {
          id: '12000814',
          text_id: '12000844-08',
        },
      ];
      let result = [];
      let found;
      data.forEach(d => {
        found = false;
        result.forEach(r => {
          if (!found && r.id === d.id) found = true;
        })
        if (!found) result.push(d);
      });
      console.log(result);

Answer №4

If you're looking for an alternative approach to achieve your desired output, here's a suggestion:
Utilize the power of the reduce method to manipulate the data and incorporate the find function to check if the current id already exists in the prev. If it does not exist, employ the filter function to eliminate duplicate id objects and only retain the first occurrence.

const data =[
  {
    id: '10000844',
    text_id: '10000844-01',
  },
  {
    id: '10000844',
    text_id: '10000844-02',
  },
  {
    id: '12000844',
    text_id: '12000844-03',
  },
  {
    id: '12000844',
    text_id: '12000844-07',
  },
  {
    id: '12000814',
    text_id: '12000844-07',
  },
 {
    id: '12002812',
    text_id: '12000844-07',
  },
   {
    id: '12000814',
    text_id: '12000844-08',
  },
]

const newData = data.reduce((prev, curr, index, arr) => {
  const find = prev.find(p => p.id === curr.id);
  if (!find) {
    const filter = arr.filter(f => f.id === curr.id);
    if (filter.length >= 1) {
      prev.push(filter[0])
    }
  }
  return prev;
}, [])

console.log(newData)

Answer №5

One way to achieve this is by utilizing the reduce method to transform the array into an object that retains only the first instance of each unique id, and then extracting the values from this modified object.

const 
  data = [{ id: "10000844", text_id: "10000844-01" }, { id: "10000844", text_id: "10000844-02" }, { id: "12000844", text_id: "12000844-03" }, { id: "12000844", text_id: "12000844-07" }, { id: "12000814", text_id: "12000844-07" }, { id: "12002812", text_id: "12000844-07" }, { id: "12000814", text_id: "12000844-08" }],
  result = Object.values(data.reduce((acc, d) => (!acc[d.id] ? { ...acc, [d.id]: d } : acc), {}));

console.log(result);

Answer №6

Some answers have been correct from the start.

IF YOU UTILIZE LODASH, CONSIDER THIS ANSWER

You have the option to utilize uniqBy.

This function will provide you with a version of the array without duplicates, keeping the first occurrence:

In your particular scenario, it would look something like this:

import uniqBy from 'lodash/uniqBy';

// Your sample data from the API
const uniqueArray = uniqBy(dataFromAPI, 'id');

Answer №7

At times, opting for a straightforward loop can be the best approach.

  1. Start by creating a temporary object
  2. Go through the data and add objects to the temporary object if their key is not found
  3. Retrieve the values from the output object

const data=[{id:"10000844",text_id:"10000844-01"},{id:"10000844",text_id:"10000844-02"},{id:"12000844",text_id:"12000844-03"},{id:"12000844",text_id:"12000844-07"},{id:"12000814",text_id:"12000844-07"},{id:"12002812",text_id:"12000844-07"},{id:"12000814",text_id:"12000844-08"}];

// Initialise the output object
const out = {};

// Loop over the array of objects
for (const obj of data) {

  // For each object destructure the id from the rest
  // of its properties 
  const { id, ...rest } = obj;

  // If there is no property on the output
  // object with that key create it by adding
  // an object composed of the id and the other
  // object properties to it
  out[id] ??= { id, ...rest };
}

// Now return an array of
// the output object's values
console.log(Object.values(out));

For more information, refer to:

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

The additional pieces of information transmitted in the state are not being accurately interpreted

I have constants set up that I want to store in the state: const day = "25/02/2020"; const timeStart = "08:00"; const timeEnd = "00:00"; In my Vuex file, I have the following setup: export default new Vuex.Store ({ s ...

Error with Webdriver/FXDriver utils.js leading to Firefox unresponsive script issue

While running browser tests with Watir webdriver and FXDriver, everything seems to be functioning well except for one test that loads a lightbox containing a large amount of HTML. When this lightbox opens, Firefox displays a popup indicating that Utils.js ...

Is there a way to sort through nested objects with unspecified keys?

I'm looking to extract specific information from a nested object with unknown keys and create a new array with it. This data is retrieved from the CUPS API, where printer names act as keys. I want to filter based on conditions like 'printer-stat ...

JavaScript query-string encoding

Can someone clarify why encodeURI and encodeURIComponent encode spaces as hex values, while other encodings use the plus sign? I must be overlooking something. Appreciate any insights! ...

Creating a Countdown in Javascript Using a Variable

I want the date to change from the first date to the second date. At the start, it should display 'Starts:' in bold followed by the remaining time. Once it switches to the second date, it should show 'Ends:' in bold and then the remaini ...

Populate a secondary dropdown menu using the selection from a primary dropdown menu and retrieve the corresponding "value" instead of displaying the value as a dropdown option

I am attempting to create two dropdowns that are populated by another dropdown. Below is the code: HTML: <form type=get action="action.php"> <select name="meal" id="meal" onChange="changecat(this.value);"> <option value="" disabled select ...

switch the visibility of the p tag based on its content

It seems like solving this shouldn't be too challenging, but I'm still learning when it comes to Javascript or JQuery. HTML: <p><span id="AddLine1Summary"></span>,</p> <p><span id="AddLine2Summary"></span& ...

Utilizing AJAX and PHP for seamless communication, retrieve and authenticate HTTPS SSL CERTIFICATE when interacting

Recently, I successfully created a node.js REST server located at . To develop the front-end, I am utilizing a combination of html, javascript, and php. However, when I attempted to implement an SSL certificate on the front-end, a problem arose: An issue ...

Exploring ways to cycle through an array of objects during a jQuery ajax request

When making a jQuery ajax call to iterate over an API response, I am encountering the issue of receiving undefined data for all elements. Can someone guide me on how to properly iterate through an array of objects in jQuery? I am new to handling iteration ...

Issue with submitting a form within a React modal - lack of triggering events

I am utilizing the npm package react-modal (https://www.npmjs.com/package/react-modal) in my project. The issue I am facing is that when I click on 'Submit', nothing happens. The function handleSubmit</a> is not being triggered, as no conso ...

Issue encountered with Express.js and connect-mongo session: "TypeError - Unable to access property 'upserted' as it is undefined"

I'm working on implementing session storage using the connect-mongo module, but I keep encountering the following error: TypeError: Cannot read property 'upserted' of undefined Here is how I'm using the connect-mongo: import session ...

Styling multiple Higher Order Components (HoCs) using Material UI withStyles

When developing my application, I encountered an issue with using Higher Order Components (HoCs) and withStyles for styling. If I apply multiple HoCs to one component, the classes prop of the first HoC gets passed to the next one in the compose chain, caus ...

Implementing script loading within the Angular scope

I'm attempting to load a custom script from the database based on client-side logic. I am having trouble figuring out how to make it function properly. Here is my controller code: 'use strict'; angular.module('youshareApp') . ...

What is the best way to manage sessions in angularjs using javascript?

Only at two specific instances in the application should the login prompt be displayed: When trying to access a page that requires login while not logged in, such as my profile page. When attempting an action that necessitates ...

Leverage the AJAX Search Lite Plugin within the top navigation of your WordPress website's header file

I am interested in utilizing the "AJAX Search Lite 3.0.6" plugin within my WordPress Theme. Plugin Link After implementing the shortcode, I noticed that it was not appearing on the navigation bar as expected: <body> <!-- Header --> & ...

Servlet question: What causes the XMLHttpRequest responseText to consistently appear empty?

I've been going crazy trying to figure out how to solve this issue. I have a servlet deployed in Tomcat running on localhost:8080 that looks like this: @WebServlet(urlPatterns = { "/createcon" }, asyncSupported = true) public class CreateCon extends ...

w3schools example showcasing the power of AJAX

How can I run this example on my local machine? http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_httprequest_js (page no longer available) I want to access the XML file hosted on w3schools without moving it to my machine. Can I run the HTML and J ...

What is the best way to retrieve data from PHP and format it into JSON for use in my jQuery script?

I need help formatting the data returned to jQuery from a query. The specific format I want is: var externalDataRetrievedFromServer = [ { name: 'Bartek', age: 34 }, { name: 'John', age: 27 }, { name: 'Elizabeth', ...

Exploring the functionality of the JavaScript switch statement across various condition scenarios

switch (true) { case (angle<20): console.log("case1") break; case (angle<70): console.log("case2") break; case (angle< ...

Merge two JSON arrays without specifying which fields to combine explicitly

After converting two Excel sheets to JSON using an online tool, two separate JSON properties were created for each sheet. The resulting JSON example looks like this: { "Product Info": [ { // Product information details here }, ...