What is the best way to eliminate duplicate categories from an array of objects?

I have an array of objects where each object contains a category, and if there are any duplicate categories, I need to only display one object for each unique category.

Below is the array:

 const costItems= [
    {
     
      amount: 1000,
      category: 'Appliances',
      instructions: '',
      subcontractor: [Object],
      thresholdAmount: null,
      thresholdPercent: null
    },
    {
      
      amount: 500,
      category: 'Appliances',
      instructions: '',
      subcontractor: [Object],
      thresholdAmount: null,
      thresholdPercent: null
    },
    {
      
      amount: null,
      category: 'Appraisal',
      instructions: '',
      subcontractor: [Object],
      thresholdAmount: null,
      thresholdPercent: null
    },
    {
     
      amount: null,
      category: 'Building Permit',
      instructions: '',
      subcontractor: [Object],
      thresholdAmount: null,
      thresholdPercent: null
    }
  ]

Is there a way to remove duplicate categories from this array of objects?

Answer №1

Explore the various loop methods available for usage.

Implementing the Array.reduce method.

const costItems = [
  { amount: 1000, category: "Appliances", instructions: "", subcontractor: [], thresholdAmount: null, thresholdPercent: null },
  { amount: 500, category: "Appliances", instructions: "", subcontractor: [], thresholdAmount: null, thresholdPercent: null },
  { amount: null, category: "Appraisal", instructions: "", subcontractor: [], thresholdAmount: null, thresholdPercent: null },
  { amount: null, category: "Building Permit", instructions: "", subcontractor: [], thresholdAmount: null, thresholdPercent: null },
];
const uniqueArray = costItems.reduce((acc, curr) => {
  const matchNode = acc.find((item) => item.category === curr.category);
  if (!matchNode) {
    acc.push(curr);
  }
  return acc;
}, []);
console.log(uniqueArray);

Answer №2

When your data is organized alphabetically in ascending order (A -> Z), you can implement the following algorithm to achieve a time complexity of O(n), making it faster than solutions using find() or indexOf() which would result in O(n^2). This approach always retains the last occurrence. A similar method can be devised to keep the first occurrence.

The concept revolves around keeping track of the last index encountered for a specific value, such as category. When a new value is encountered, the algorithm references that index to retrieve the previous value, which due to the sorted order, is guaranteed to be the final occurrence.

const costItems= [
    {
     
      amount: 1000,
      category: 'Appliances',
      instructions: '',
      subcontractor: "Appliance last occurrence",
      thresholdAmount: null,
      thresholdPercent: null
    },
    {
      
      amount: 500,
      category: 'Appliances',
      instructions: '',
      subcontractor: "Appliance last occurrence",
      thresholdAmount: null,
      thresholdPercent: null
    },
    {
      
      amount: null,
      category: 'Appraisal',
      instructions: '',
      subcontractor: "Appliance first and last occurrence",
      thresholdAmount: null,
      thresholdPercent: null
    },
    {
     
      amount: null,
      category: 'Building Permit',
      instructions: '',
      subcontractor: "Appliance first and last occurrence",
      thresholdAmount: null,
      thresholdPercent: null
    }
  ]
  
  function removeDuplicatesKeepLastOccurrence(items, key){
    if(items.length < 2) return items.slice();
    let prev = 0;
    const result = [];
    items.forEach((value, i, items) => {
      if(items[prev][key] !== value[key]) result.push(items[prev])
      prev = i;
    })
    result.push(items[items.length - 1])
    return result;
  }
  
  console.log(removeDuplicatesKeepLastOccurrence(costItems, "category"))

I've indicated occurrences with first or last so you can easily identify that only the final occurrences are included in the result.

Answer №3

Just a quick one-liner

const items = [{price:200,category:"Electronics",description:"",manufacturer:[],minimumPrice:null,maximumPrice:null},{price:100,category:"Clothing",description:"",manufacturer:[],minimumPrice:null,maximumPrice:null },{price:null,category:"Furniture",description:"",manufacturer:[],minimumPrice:null,maximumPrice:null},{price:null,category:"Kitchenware",description:"",manufacturer:[],minimumPrice:null,maximumPrice:null}];

const summary = Object.values(items.reduce((result, item) => (result[item.category] ??= item, result), {}));

console.log(summary);
.as-outlet-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

Node's original file name

Is there a way to retrieve the original filename from a file that has an absolute path in node.js? In node.js, I can use path.basename to get the name and base URL, and fs.stats for more detailed information like: Stats { dev: 2114, ino: 48064969, ...

A JointJS element with an HTML button that reveals a form when clicked

How do I bind data to a cell and send it to the server using the toJSon() method when displaying a form on the addDetail button inside this element? // Custom view created for displaying an HTML div above the element. // ---------------------------------- ...

Fixing PNG Fading Issue in Internet Explorer 8

I am currently utilizing the jQuery Cycle plugin to produce a fading animation effect. While this works perfectly on most browsers, I have encountered an issue with PNG files containing semi-transparent pixels in Internet Explorer 8. These partially transp ...

How to show dates in AngularJS using local formatting

One situation I'm dealing with involves setting a date for an event. The challenge is that the date picker needs to display the date in a localized format based on the country or region. I've been exploring various solutions in AngularJS, but so ...

If the checkbox is selected, include an anonymous email in the field and conceal the field

I am looking to enhance my Feedback form by providing users with the option to submit feedback anonymously. However, my CMS requires both Email and Name fields to be mandatory. To address this, I am considering adding a checkbox that, when selected, auto ...

When the form is submitted, I am unable to record the checkbox value

Hi, I have a question regarding submitting a form to the "/delete" route when a checkbox is checked. Although I am able to submit the form successfully, I am facing an issue retrieving the checkbox value that I assigned using ejs. Below are the relevant co ...

Tips for resolving the issue: SyntaxError - Unexpected token import

I've encountered this error in the past and have looked at other solutions, but none of them seem to work for my specific issue. My package.json file includes the following dependencies: "dependencies": { "axios": "^0.15.2", "babel": "^6.5. ...

Creating dynamic form groups that allow for the addition and removal of forms while assigning unique identifiers and names to each input field

I am currently immersed in the development of a sophisticated CMS system. My main objective is to dynamically add and remove form inputs using JavaScript upon clicking a button, with the ultimate goal of submitting the data into a database via PHP script. ...

What is the best method to implement a function on groups within an array using R?

I am dealing with a 3D array that consists of latitude, longitude, and datetime (Year_Month_Day_Hour). In R, what is the most effective way to apply a function over the array by grouping them based on years, months, or days? The desired outcome is an array ...

What is the proper way to utilize a template literal within an import declaration?

Upon executing the following line: import stats from `./${process.env.STATS}` An error message is shown: Parsing error: Unexpected token ` To successfully load the module, use the following expression: const stats = require(`./${process.env.STATS}`) ...

Tips for generating AJAX requests directly from HTML documents

Hey there! I'm fairly new to JavaScript and have a question that might seem silly to some. How exactly can I invoke a function from a Coffeescript file within my HTML code? I'd like to give users the option to choose the language in which they v ...

Exploration of features through leaflet interaction

Attempting to plot bus routes on a map using leaflet with geojson for coordinates. Facing issues with making the bus line bold when clicked, and reverting the style of previously clicked features back to default. Current Progress function $onEachFeature( ...

What could be causing default props to malfunction in this particular scenario?

I've been learning about default props and encountered a problem. Can someone clarify why default props are not functioning in this scenario? import React from 'react'; import PropTypes from 'prop-types'; import defaultImage from & ...

What is the reason behind Ramda having multiple curry functions in its source code, much like Redux having multiple compose functions?

There are _curry1, _curry2, _curry3, and _curryN functions within the depths of Ramda's source code This interesting pattern is also utilized in the redux compose function I find myself pondering: why did they choose this intricate pattern over a mo ...

Preflight response indicates that the Access-Control-Allow-Methods does not permit the use of the PATCH method

Implementing the axios PATCH method in my ReactJS project to update a record is resulting in a failure with the following error message: Failed to load : Method PATCH is not allowed by Access-Control-Allow-Methods in preflight response. Below is the co ...

The pop-up window created programmatically refuses to close

I am struggling with an issue where I am opening a pop-up from the code behind as a waiting image while processing some background activities. However, the pop-up does not close after the activity is done. Can someone please help me figure out what I am ...

Designing a Curved Stepper Component in the Shape of an S

I've been attempting to create a custom stepper component with an S-curve shape using React, but so far I haven't been successful. I even tried utilizing the MUI Stepper component and experimented with pure HTML and CSS, but couldn't achieve ...

I duplicated a functional jQuery form and moved it to a different location, but I am only able to get the

I recently duplicated a jQuery form from one page to another, but encountered unexpected issues with the copied version. The original form functions as follows: An onclick function connected to an image triggers a confirmation modal window with an "OK" bu ...

Having difficulty grasping the significance of the data received from the API response

Currently, as I am working on my personal Portfolio for a Web Developer course, I have encountered an issue with correctly implementing my API to retrieve information from the database. Previously, I faced no problem when using a .json file, but now, I am ...

JavaScript code for validating two passwords is malfunctioning

I'm currently working on a registration form for my website and I'm trying to implement a JS script that compares two password inputs (password and repeat password) and displays a message saying "passwords are not the same." Below is the code I h ...