Eliminate repetitive elements within an array of objects

Is there a way to eliminate duplicate values in an object array using Javascript?

0: {d: “2021/01/19”, color: “#009988"}
1: {d: “2021/01/19”, color: “#CC3311"}
2: {d: “2021/01/19”, color: “#009988"}
3: {d: “2021/01/19”, color: “#009988"}
4: {d: “2021/01/20”, color: “#009988"}
5: {d: “2021/01/22”, color: “#009988"}

I am looking to filter this object array as follows:

0: {d: “2021/01/19”, color: “#009988"}
1: {d: “2021/01/19”, color: “#CC3311"}
2: {d: “2021/01/20”, color: “#009988"}
3: {d: “2021/01/22”, color: “#009988"}

I attempted to achieve this by implementing the given code, but it did not produce the expected result.

    for (let i = 0; i < array.length-1; i++) {
      if (arr[i].d === array[i+1].d) {
        if (array[i].color === array[i+1].color) {
          array.splice(i, 1);
          i--;
        }
      }
    }

Answer №1

Remove duplicates from an array of objects based on specific properties

Answer №2

const initialData = [
  { date: "2021/01/19", shade: "#009988"},
  { date: "2021/01/19", shade: "#CC3311"},
  { date: "2021/01/19", shade: "#009988"},
  { date: "2021/01/19", shade: "#009988"},
  { date: "2021/01/20", shade: "#009988"},
  { date: "2021/01/22", shade: "#009988"}
];

const uniqueResult = [];

initialData.forEach((item) => {
  if (!(uniqueResult.some(dataItem => dataItem.date === item.date && dataItem.shade === item.shade))) {
    uniqueResult.push(item)
  }
});

Answer №3

let data=[{date:"2021/01/19",hex:"#009988"},{date:"2021/01/19",hex:"#CC3311"},{date:"2021/01/19",hex:"#009988"},{date:"2021/01/19",hex:"#009988"},{date:"2021/01/20",hex:"#009988"},{date:"2021/01/22",hex:"#009988"}];

const uniqueData = data.filter((element,index,arr) => 
  arr.findIndex(item => item.date === element.date && item.hex === element.hex) === index
)

console.log(uniqueData)
.as-console-wrapper { max-height: 100% !important; top: 0; } /* ignore this */

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

refusing to display the pop-up in a separate window

Hi there, I'm having an issue with a link that's supposed to open in a pop-up but is instead opening in a new tab. I'd like it to open in a proper pop-up window. <button class="button button1" onclick=" window.open('te ...

Angular 2 - synchronizing timer for all users

I have developed a timer that needs to function consistently for all users at the same time. To achieve this, I stored the start_time (timestamp when the timer begins) in my database and implemented the following code snippet to calculate the remaining ti ...

Tips for creating a unique custom UI headline using ReactJS, CSS, and bootstrap

Looking to create a design that is responsive in ReactJS using Bootstrap or CSS if needed. I need assistance with placing separators between columns and ensuring the values of each label are aligned in the same column but on the next line. The layout shoul ...

Issues with AngularJS ng-bind-html failing to display list items

I am working with a basic HTML document that looks like this... <ol> <li><strong>Test 1</strong></li> <li><strong>Test 2</strong></li> </ol> ...and I am attempting to connect it to a div ...

Tips on creating a button that, upon clicking, triggers the download of an Excel file using PHPSpreadsheet

I am trying to figure out how to create a button that, when clicked, will download an Excel file named b1b5.xls with some specified values added. Here is the code I have so far: <html> <head> </head> <body> <center> < ...

Merging Two Angular Pages within a Jhipster Application

My jhipster application is simple, generating 2 entities: Product and Category. The generated pages to list the data for these entities can be found here. Specifically, there are pages for Product and Category. If I want to create a new page that combines ...

What is the method for incorporating an onmouseover event into child states while extending the parent state controller?

I have a basic angularjs controller coupled with jquery that triggers a console log message when the mouse hovers over an anchor element: app.controller('MenuController', function() { $("a").on('mouseover', function (e) { c ...

Storing the API key returned by the Node.js store as a variable was

Just starting out with node and experimenting with A node.js library for the Pardot API I provide my userKey, email, and password to pardot, which returns an api_key. This is the code snippet I am using for authentication. Upon running my node server, I ...

Guidelines for incorporating Angular variables into jQuery scripts

I have a form with an input field that dynamically generates a list of names using Angular. My goal is to turn each name into a clickable link that will submit the form with that specific name as the input value. <form method="POST" action="/results/" ...

Content not being displayed by Javascript

I'm having trouble displaying content using JavaScript DOM. Every time I try to run my code, the page comes up blank. Here is an example of my HTML file: <!DOCTYPE html> <html> <head> <title>Radiant HQ</titl ...

Breaking down and modifying JavaScript JSON objects

Can someone explain how to separate a JSON object and make updates based on the ID? I've heard about using stringify! But how do I actually implement the function to update the object? <input type="text" value="{"id":"1","price":"30.00","edit":0}, ...

Stopping a parent's event from firing when clicking on child elements without interfering with the child element events

Having read several posts such as this one, I am exploring a method to click on the parent div for it to hide, without hiding when clicking on either the search box or the 'click for event 2' text. I have tried using onclick stop propagation to ...

Showing formatted JSON (Large Object) on an HTML page

Having trouble displaying formatted JSON in an HTML page, especially when dealing with larger objects (an array of objects). The current method involves using JSON.stringify(data) to display the JSON object upon receiving a response from the server. The P ...

Implementing visibility toggles for objects in three.js using a graphical user interface

I am interested in controlling the visibility of objects in my scene through a button on a GUI. The following function currently hides/shows objects individually: g3white.traverse(function(child){child.visible = true;}); g3black.traverse(function(child){ ...

Switching background images with Javascript through hovering

I am currently working on implementing a background changer feature from removed after edits into my personal blog, which is only stored on my local computer and not uploaded to the internet. However, I am unsure of what JavaScript code I need to achieve t ...

Using window.open in Google Chrome results in multiple tabs being opened instead of just one

I have a dynamic input field with a search button. Initially, only one tab is opened when I click the button. But after saving and clicking it again, multiple tabs open for the same URL. The number of tabs is equal to the number of dynamic input fields cre ...

Using Node.js to alter an existing JSON file

I have a file named a1.json that contains the following data: { "Key1" : [ { "Key11" : "Value11" , "Key12" : "Value12" }, { "Key21" : "Value21" , "Key22" ...

Determine line-height and adjust positions using JavaScript in the Chrome browser

I am creating a basic text reading application with a line to aid in easy reading. The functionality involves using the up and down arrow keys on the keyboard to adjust the position of a red line based on the line-height property. This is accomplished thr ...

What is the reason behind the failure to update the state via a reducer and Object.assign?

I'm attempting to develop a reducer without utilizing ES6. It's an outmoded PHP application that lacks a build process for transpilation. I am initializing the state: let defaultState = { accountTypes: { individual: { c ...

Ensure no duplicate values are added to the array during population

I am encountering an issue with populating an array with 6 randomly generated numbers. The process involves generating a random number between 1 and 49, checking it against existing numbers in the array, and adding it to the array if no duplicates are foun ...