eliminating identical items in an array

I've been working on finding and removing duplicate objects in an array, but I keep encountering an error when trying to access the filterList[i+1].tagID element. Strangely, manually inputting the [i+1] values seems to yield the correct results. I'm puzzled as to why the i+1 reference is causing an issue. Additionally, I've been considering whether using a slice[i, 1] method would be more effective than delete.

const filterList = [{
  tagID: 1,
  tagName: "Red"
}, {
  tagID: 1,
  tagName: "Red"
}, {
  tagID: 2,
  tagName: "Orange"
}, {
  tagID: 2,
  tagName: "Orange"
}, {
  tagID: 5,
  tagName: "Blue"
}, {
  tagID: 5,
  tagName: "Blue"
}, {
  tagID: 5,
  tagName: "Blue"
}, {
  tagID: 6,
  tagName: "Indigo"
}, {
  tagID: 6,
  tagName: "Indigo"
}, {
  tagID: 7,
  tagName: "Violet"
}, {
  tagID: 7,
  tagName: "Violet"
}, {
  tagID: 7,
  tagName: "Violet"
}]

filterList.sort(function(a, b) {
  return a.tagID - b.tagID;
});

for (let i = 0; i < filterList.length; i++) {
  if (filterList[i].tagId == filterList[i+1].tagID) {
    delete filterList[i];
  }
}

console.log(filterList)

Answer №1

Give this method a shot! Utilize filter along with es2015

const filterListResult = filterList.filter((item, index, self) => index === self.findIndex((t) => (t.tagID === item.tagID && t.tagName === item.tagName)));
console.log(filterListResult);
<script>
const filterList = [{
  tagID: 1,
  tagName: "Red"
}, {
  tagID: 1,
  tagName: "Red"
}, {
  tagID: 2,
  tagName: "Orange"
}, {
  tagID: 2,
  tagName: "Orange"
}, {
  tagID: 5,
  tagName: "Blue"
}, {
  tagID: 5,
  tagName: "Blue"
}, {
  tagID: 5,
  tagName: "Blue"
}, {
  tagID: 6,
  tagName: "Indigo"
}, {
  tagID: 6,
  tagName: "Indigo"
}, {
  tagID: 7,
  tagName: "Violet"
}, {
  tagID: 7,
  tagName: "Violet"
}, {
  tagID: 7,
  tagName: "Violet"
}]
</script>

Answer №2

To eliminate duplicate IDs, you can utilize the set object. Then, by using the map and find functions, you can modify the outcome to display only the initial occurrence of each tagID.

 Array.from(new Set(filterList.map(_=> _.tagID)))
  .map(ID=> filterList.find(o=> o.tagID === ID)));

const filterList = [{
  tagID: 1,
  tagName: "Red"
}, {
  tagID: 1,
  tagName: "Red"
}, {
  tagID: 2,
  tagName: "Orange"
}, {
  tagID: 2,
  tagName: "Orange"
}, {
  tagID: 5,
  tagName: "Blue"
}, {
  tagID: 5,
  tagName: "Blue"
}, {
  tagID: 5,
  tagName: "Blue"
}, {
  tagID: 6,
  tagName: "Indigo"
}, {
  tagID: 6,
  tagName: "Indigo"
}, {
  tagID: 7,
  tagName: "Violet"
}, {
  tagID: 7,
  tagName: "Violet"
}, {
  tagID: 7,
  tagName: "Violet"
}]

let result = Array.from(new Set(filterList.map(_ => _.tagID))).map((ID, index) => filterList.find(o => o.tagID == ID));

console.log(result);

Answer №3

To start the iteration, you can begin from index 1 and compare the last element with the current one.

const filterList = [{ tagID: 1, tagName: "Red" }, { tagID: 1, tagName: "Red" }, { tagID: 2, tagName: "Orange" }, { tagID: 2, tagName: "Orange" }, { tagID: 5, tagName: "Blue" }, { tagID: 5, tagName: "Blue" }, { tagID: 5, tagName: "Blue" }, { tagID: 6, tagName: "Indigo" }, { tagID: 6, tagName: "Indigo" }, { tagID: 7, tagName: "Violet" }, { tagID: 7, tagName: "Violet" }, { tagID: 7, tagName: "Violet" }]

filterList.sort(function(a, b) {
    return a.tagID - b.tagID;
});

for (let i = 1; i < filterList.length; i++) {
    if (filterList[i - 1].tagId === filterList[i].tagID) {
        delete filterList[i];
    }
}

console.log(filterList);

Answer №4

Create a fresh list through the use of the reduce method:

const filterList = [{ tagID: 1, tagName: "Red" }, { tagID: 1, tagName: "Red" }, { tagID: 2, tagName: "Orange" }, { tagID: 2, tagName: "Orange" }, { tagID: 5, tagName: "Blue" }, { tagID: 5, tagName: "Blue" }, { tagID: 5, tagName: "Blue" }, { tagID: 6, tagName: "Indigo" }, { tagID: 6, tagName: "Indigo" }, { tagID: 7, tagName: "Violet" }, { tagID: 7, tagName: "Violet" }, { tagID: 7, tagName: "Violet" }]

const newList = filterList.reduce((total, current) => {
    const exist = total.some(t => t.tagID === current.tagID)
    if (!exist) {
        total.push(current)
    }
    return total
}, [])

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

Testing for expressjs 4 using Mocha revealed unexpected behavior when attempting to spy on a function called within a promise. Despite setting up the

I have encountered a situation with some test cases structured like this: it('does stuff', function(done) { somePromise.then(function () { expect(someSpy).to.have.been.called done() }) }) When the assertion in a test case fails, it ...

Tips for uploading arrays in Node.js´s:1. Use the `

Can someone help me with posting multiple arrays simultaneously? Here is what I am trying to achieve: { name:"John Snow", detail: [ {size: "M", total: 5, color: "red"}, {size: "S", total: 2, color: "bl ...

Utilizing AngularJS Directive to trigger a designated function upon change in an input file

My current project involves creating a scavenger hunt editor with various types of questions stored in an array. Each question can be of a different type, all displayed using ng-repeat. To achieve this, I utilize a JavaScript object representing a Questio ...

Troubleshoot: JQuery unable to change background color in code

Is there a way to use JQuery to cycle through an array of colors and change the background color of a page whenever a specific button is clicked? I've tried implementing it with the following code, but it doesn't seem to work as expected. Here&a ...

Renew The Dining Surface

I am looking for a way to update the table content without refreshing the entire page. I am using HTML, CSS, and JavaScript to display the current data from my sqlite3 database. Any tips on how to achieve this would be appreciated. ...

Creating a conditional statement within an array.map loop in Next.js

User Interface after Processing After retrieving this dataset const array = [1,2,3,4,5,6,7,8] I need to determine if the index of the array is a multiple of 5. If the loop is on index 0, 5, 10 and so on, it should display this HTML <div class="s ...

JavaScript XML Serialization: Transforming Data into Strings

When trying to consume XML in an Express server using express-xml-bodyparser, the resulting object is not very useful. This is the XML: <SubClass code="A07.0"/> <SubClass code="A07.1"/> <SubClass code="A07.2"/> <SubClass code="A07.3" ...

When the document is shifted by an angular function call, the mouseup event fails to trigger

My problem involves an angular function that alters the ng-if state to display the sidebar when the image is clicked. However, upon calling the function and shifting the entire webpage, the mouseup event for the image no longer triggers when I release th ...

The chosen option does not display any information

I am new to databinding an html control using ajax for the first time. After checking and debugging my ajax call, I can see that the data is retrieved successfully, but it does not show up in the select option. My javascript code is positioned at the botto ...

After ReactDOM is used, the JavaScript code is no longer functioning properly

While working on my latest project, I utilized react.js and encountered an issue where javascript seemed to stop working when using ReactDOM to render a class extended from React.Component. I noticed that the alert() method would not work if it was placed ...

Is there a way to decode/compile/interpret the data within nested HTML tags within my AngularJS directives?

How can I process/compile/resolve the contents of enclosed HTML in my directives. The specific directive being discussed is: angular.module('transclude', []) .directive('heading', function(){ return { restrict: 'E&apos ...

Determining the length and angle of a shadow using X and Y coordinates

I'm currently tackling the task of extracting data from a file generated by a software program that has the ability to add a shadow effect to text. The user interface allows you to specify an angle, length, and radius for this shadow. https://i.stack ...

Encountering an undefined value from state when implementing useEffect and useState

One issue I am facing is that the state of my projects sometimes returns as undefined. It's puzzling to me why this happens. In the useEffect hook, I have a function that fetches project data from an API call to the backend server. This should return ...

Change a Character or Word in JavaScript after it's been typed

If I were to type the word "hello" into a textarea, is there a way for me to select that specific word and modify it afterwards? For instance, let's say I typed hello without hitting the space bar; could the system recognize this word and automaticall ...

The operator in Javascript that uses question marks for conditionals is known as the

I understand that the expression: return A ? B : C translates to If A is true, return B; otherwise, return C But how should I interpret the following: return A ? B ? C : D : E This code is not mine; I simply want to comprehend it. I came across this a ...

Eliminate placeholder text when the tab key is pressed

I'm currently facing an issue with a textarea that has a placeholder and the Tab key functionality in Internet Explorer. I've included placeholder.js to make it work, but when I repeatedly press the tab key and focus on the textarea, the placehol ...

The Protractor option is nowhere to be found on the Run Configuration popup window in Eclipse

Issue with Protractor in Eclipse: Unable to locate Protractor option on Run Configuration popup. Despite following the steps outlined in http://www.protractortest.org/#/ and this guide on configuring Protractor with Eclipse (specifically the 2 Answer step ...

Transferring UTM parameters to a different page via a button click

Is there a way to extract parameters from a URL after the "?" and add them to a button's href in order to redirect to another landing page? I want to transfer UTM parameters to another page using JavaScript within the button. Original Homepage: Dest ...

Express.js - Struggling with Setting the Content-Type Response Header

While using Express.js, I am facing an issue with setting the Content-Type header. Even after specifying it as text/html, the response is being sent with application/octet-stream. Below is the snippet of my code: const express = require("express" ...

What is the syntax for defining parameters in an overloaded arrow function in TypeScript?

Trying to create an async arrow function that can handle a single image object or an array of image objects. I'm new to TypeScript overloading and may be approaching this the wrong way. Here's what I've come up with: type ImageType = { ...