Having trouble with making the function to remove duplicate items from a JavaScript array?

Before anything else, I want to acknowledge that there are numerous answers on SO regarding this issue. However, I am encountering some difficulties with them, which is why I am posting a new question on the topic.

Here is my Array of Objects:

0: {id: 'lAYOUT', label: 'lAYOUT', items: 'val1'}
1: {id: 'tecst', label: 'tecst', items: 'val1'}
2: {id: 'tecst', label: 'tecst', items: 'val1'}

I am attempting to filter out so that there are only 2 unique values, as there are 2 duplicate objects in the array. My goal is to create distinct objects based on items and label.

This is how I am trying to achieve it using lodash:

const filteredArray = uniq(nestedItems, (item, key, a) => item.items && item.label)

However, it keeps returning all 3 elements instead.

I also tried the following approach:

const filteredArray = [...new Set(nestedItems)]

Answer β„–1

Utilizing the Filter method to extract the specific object's value, index, and array. By using the FindIndex function, we can target a particular object within the array. Then, we compare the filter object with the findindex object, pushing it into a new array if they do not match, resulting in a unique array!

Give this code snippet a try!

 let arr = [{ id: 'lAYOUT', label: 'lAYOUT', items: 'val1' },
    { id: 'tecst', label: 'tecst', items: 'val1' },
    { id: 'tecst', label: 'tecst', items: 'val1' }];

    let newArr = arr.filter((value, index, self) =>
      index === self.findIndex((t) => (
        t.label === value.label && t.items === value.items
      ))
    );
    console.log(newArr, 'newArr');

Answer β„–2

Utilize hash grouping for filtering by multiple keys:

const data = [{ id: 'lAYOUT', label: 'lAYOUT', items: 'val1' }, { id: 'tecst', label: 'tecst', items: 'val1' }, { id: 'tecst', label: 'tecst', items: 'val1' }];

const unique = Object.values(data.reduce((acc, obj) => {
  const hash = `${obj.id}-${obj.label}`;
  acc[hash] = obj;
  return acc;
}, {}));

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

Same outcome using lodash

const data = [{ id: 'lAYOUT', label: 'lAYOUT', items: 'val1' }, { id: 'tecst', label: 'tecst', items: 'val1' }, { id: 'tecst', label: 'tecst', items: 'val1' }];

const result = _.uniqWith(data, (o1, o2) => `${o1.id}-${o1.label}` === `${o2.id}-${o2.label}`);

console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.js" integrity="sha512-2iwCHjuj+PmdCyvb88rMOch0UcKQxVHi/gsAml1fN3eg82IDaO/cdzzeXX4iF2VzIIes7pODE1/G0ts3QBwslA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Answer β„–3

const information = [
  { id: 'id1', description: 'description1', content: 'content1' }, 
  { id: 'id2', description: 'description2', content: 'content2' },
  { id: 'id1', description: 'description1', content: 'content2' }
];

const filterUnique = (...keys) => [
    ...new Map(information.map(info => [keys.map(key => info[key]).join(), info])).values()
];

console.log(1, filterUnique('description'));
console.log(2, filterUnique('description','content'));

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

I'm looking for a JQuery plugin that can lock an element in place as you scroll through a webpage

My query is not regarding position:fixed. While scrolling down the page, I aim for the element to move down along with the page until it goes beyond the view of the browser. Once it goes out of the view, it should stay close to the top of the page, yet st ...

My custom function is not invoking the Firebase function createUserWithEmailAndPassword

The function createUserWithEmailAndPassword is not being triggered within the SignUpUser function when the onClick event occurs. However, it works when I use onClick={signUpUser(email,password)} import React from 'react'; import styled from &apo ...

Converting Arrays to Strings in JavaScript

Here is the code that is causing me trouble. var http = require("http"); var i = 0; var hostNames = ['www.1800autoland.com','www.youtube.com','www.1800contacts.com']; for(i;i<hostNames.length;i++){ var options = { ...

Find elements that are not contained within an element with a specific class

Imagine having this HTML snippet: <div class="test"> <div class="class1"> <input type="text" data-required="true"/> </div> <input type="text" data-required="true"/> </div> I'm looking to select ...

Include the data-title attribute within the <td> elements of my datatables

To apply the magic of jQuery datatables to all my tables, I use datatables. For responsive tables, I add data-title to my td's. Is there a way to automatically add data-title to all my td's like below? <td data-title="Fruit">Apple</td&g ...

retrieve: add elements to an array

I'm having trouble identifying the issue here. I am fetching some json data (using a text file) and trying to push it into an array in the global scope. Even though I iterate over the json and push entries to the array, when I log it out, it appears e ...

Steps for deploying an ejs website with winscp

I have developed a Node.js web application using ExpressJS, with the main file being app.js. Now I need to publish this website on a domain using WinSCP. However, WinSCP requires an index.html file as the starting point for publishing the site. Is there ...

developing an associative object/map in JavaScript

I have a form featuring various groups of checkboxes and I am attempting to gather all the selected values into an array, then pass that data into an Ajax request. $('#accessoriesOptions input').each(function(index, value){ if($(this).prop(& ...

Display a preview of a React component

Currently facing a challenge where I need to create a form for users to adjust the title, background color, button background, text color, and other settings of a component. I want to provide a live preview of the component as the user makes changes. I en ...

Easily use Discord.JS 13 slash commands to generate an embed displaying a user's specific role within a server

Currently, I am in the process of creating a slash command that will reveal a user's specific roles when the command is triggered. run: async (client, interaction) => { try{ const { member, channelId, guildId, applicationId, comman ...

How can I use jQuery to set up form validation for an input textfield?

Check out this code snippet: <form data-test="loginForm-container" novalidate="" method="POST" enctype="multipart/form-data"> <div class="css-o5d3v1 e1ovefus2"> <div data-test="guestForm-email-wrapper" class="e1ovefus1 css-yjv4po e1eu3s ...

Passport appears to be experiencing amnesia when it comes to remembering the user

After extensive research online, I have yet to find a solution to my issue. Therefore, I am reaching out here for assistance. I am currently working on implementing sessions with Passport. The registration and login functionalities are functioning properl ...

Leveraging the $dirty property in AngularJS to determine if any changes have been made to a form

Recently, I've been attempting to determine if my form is being edited by monitoring certain fields. I've come across $dirty as a potential solution for this task, but unfortunately, I'm struggling to identify what exactly I'm overlooki ...

The PageMethods function is successful when using a single parameter, but encounters an error when attempting to use two parameters, resulting in the

PageMethods worked perfectly when sending a single parameter to a code-behind aspx page. However, I encountered the error "Unknown web method" when attempting to provide two parameters (or an Object other than a String). The functional code in my aspx pag ...

Issue with React/D3.js Density Plot - Error: The <path> attribute d is expecting a number, but received "M10,NaNL12,NaNC14,Na…"

I'm currently working on implementing a Density Plot in React using D3.js, but unfortunately, the plot is not appearing on the screen. Since I don't have much experience with charts and data visualization, I've been trying to follow the exam ...

How can I avoid duplicating code in HTML? I find myself utilizing the Bootstrap 4 collapse feature around 20 times on a single page

<div class="card" style> <div class="card-header" id="headingOne"> <h5 class="mb-0"> <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria- expanded="true" aria-controls="collapseO ...

Discovering the greatest difference in length between strings from two arrays

After attempting to solve this using a nested loop and storing the lengths in an int array to find the highest number, it seems like I may be complicating things unnecessarily. Perhaps there is a simpler way to approach this problem. Here is the code sni ...

The removal of an object becomes unsuccessful when objects with lower indices have been deleted beforehand

Attempting to construct a multi-layer object representing a program; check out my progress here http://codepen.io/Irish1/pen/lbjdw Imagine adding 3 weeks, each with 3 days, and each day having 3 sessions. Removing these objects is feasible as long as caut ...

The $(document).ready function may not be compatible with Internet Explorer

I have a page with two links - one for registering and one for logging in. Currently, the register link is the most important. When clicked, it loads a .tpl file using jQuery's load function. Within this tpl file, I include a new JavaScript file usin ...

Substitute names and make copies in a bash associative array

My bash script is designed to determine if the input date ($1) falls within a specified date range. The user must provide a date as well as specify whether to check against range a or b ($2). #!/usr/bin/env bash today=$(date +"%Y%M%d") declare -A dict=$2 ...