Filtering out customized repetitive objects from an array using JavaScript

Given an array of objects like the one below, I need to selectively filter out repetitive keys in order to address specific duplicates without removing all instances.

var arr = [
    {id: 1, value: 'John'},
    {id: 2, value: 'John'}, // Should be filtered
    {id: 3, value: 'John'}, // Should be filtered
    {id: 4, value: 'John'}, // Should be filtered
    {id: 5, value: 'Alex'},
    {id: 6, value: 'Louis'},
    {id: 7, value: 'David'},
    {id: 8, value: 'David'}, // Should not be filtered

]

Desired Result:

arr = [
    {id: 1, value: 'John'},
    {id: 5, value: 'Alex'},
    {id: 6, value: 'Louis'},
    {id: 7, value: 'David'},
    {id: 8, value: 'David'},

]

I have attempted the following solution so far:

arr = arr.reduce((a, b) => {
    if (!a.some(x => x.description === b.description)) a.push(b);
    return a;
}, []);

Thank you in advance.

Answer №1

If you're interested in removing duplicates and maintaining the first item, one way to do this is by using a closure with a Set for filtering.

const
    array = [{ id: 1, value: 'John' }, { id: 2, value: 'John' }, { id: 3, value: 'John' }, { id: 4, value: 'John' }, { id: 5, value: 'Alex' }, { id: 6, value: 'Louis' }, { id: 7, value: 'David' }, { id: 8, value: 'David' }],
    keep = ['David'],
    result = array.filter(
        (s => ({ value }) => keep.includes(value) || !s.has(value) && s.add(value))
        (new Set)
    );

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

Answer №2

Implementing a solution using the Set data structure along with an array or set containing exceptions.

var items = [
    {id: 1, name: 'John'},
    {id: 2, name: 'John'}, // Should be excluded
    {id: 3, name: 'John'}, // Should be excluded
    {id: 4, name: 'John'}, // Should be excluded
    {id: 5, name: 'Alex'},
    {id: 6, name: 'Louis'},
    {id: 7, name: 'David'},
    {id: 8, name: 'David'}, // Should not be excluded

]

const filterDuplicates = (items, exceptions) => {
  const values = new Set();
  return items.filter(item => {
    if(values.has(item.name) && !exceptions.includes(item.name)){
      return false;
    } else {
      values.add(item.name);
      return true;
    }
  })
}

console.log(filterDuplicates(items, ["David"]));

Answer №3

To determine if a value has already been encountered, you can utilize Array#filter along with a boolean indicator.

var data = [
    {id: 1, value: 'Alice'},
    {id: 2, value: 'Alice'}, // Should be removed
    {id: 3, value: 'Alice'}, // Should be removed
    {id: 4, value: 'Alice'}, // Should be removed
    {id: 5, value: 'Bob'},
    {id: 6, value: 'Charlie'},
    {id: 7, value: 'David'},
    {id: 8, value: 'David'}, // Should not be removed
];
const filterDuplicates = (data, val)=>{
  let check = false;
  return data.filter(({value})=>value !== val || (!check && (check = true)));
};
console.log(filterDuplicates(data, 'Alice'));

Answer №4

let array = [
  { id: 1, value: "John" },
  { id: 2, value: "John" }, // Filtered out
  { id: 3, value: "John" }, // Filtered out
  { id: 4, value: "John" }, // Filtered out
  { id: 5, value: "Alex" },
  { id: 6, value: "Louis" },
  { id: 7, value: "David" },
  { id: 8, value: "David" }, // Should not be filtered
];

const filteredArray = Array.from(
  array.reduce((filtered, item) => {
    if (!filtered.has(item.value)) {
      filtered.set(item.value, item);
    }
    return filtered;
  }, new Map()).values()
);

console.log(filteredArray);

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

Error encountered when attempting to send JSON data with special characters via a POST or PUT request using node.js's http.request()

While attempting to use the node.js http module to PUT a JSON data into CouchDB, I encountered an issue. The JSON included a special character "ä" which caused CouchDB to respond with an "invalid_json" error. However, once the special character was remove ...

Show the template when the link is clicked using Angular directive

Perhaps the question is not phrased properly, but here is the idea I am working on. I have a navbar set up with an array of countries that includes their names and coordinates. <body> <nav class="navbar navbar-default"> <div cl ...

The issue with Vue Router is that it fails to display the intended component

I am facing an issue with nested routes in vue-router, specified in the router.js file. After logging in, the Query and Result links in the Header section always display the Register and Login components, even though my Vuex setup seems correct based on my ...

Tips on entering a text field that automatically fills in using Python Selenium

One of the challenges I am facing on my website is an address input text field that gets automatically populated using javascript. Unlike a drop-down field where you can select values or a standard text field where you can manually type in information, thi ...

Discover the technique for splitting a string using jQuery with multiple strings as separators

I am looking to split a string in jQuery or JavaScript using multiple separators. When we have one string as a separator, our code looks like this: var x = "Name: John Doe\nAge: 30\nBirth Date: 12/12/1981"; var pieces = x.split("\n"), p ...

Searching for elements using jQuery's "attribute-based" selector

Check out this straightforward example on jsfiddle: HTML: <input type="text"/> <input type="text" value="aaa"/> JS: $("input:first").val("aaa"); alert($("input[value='aaa']").length);​ Have you ever wondered why Chrome and IE g ...

Revert animation back to its initial position with the help of JavaScript

After implementing the script below, I successfully managed to shift my image to the right upon clicking: <script> var myTimer = null; function move(){ document.getElementById("fish").style.left = parseInt(document.getElementById("fish ...

What is causing the error to occur during the installation of the NestJS Client?

Encountered an error while attempting to install the nestjs client, and I'm completely puzzled by this issue. PS C:\Users\meuser> npm i -g @nestjs/cli npm ERR! code ETARGET npm ERR! notarget No matching version found for @angular- ...

Using Angular 2 to assign a pipe dynamically from a variable

Could something like the following be achievable: {{property | some_variable_name}} I am aiming to utilize a pipe that is defined in a JSON configuration (or variable), but I am uncertain if it is feasible to include the pipe name within the interpolatio ...

Steps to obtain the precise source code of a webpage

Is there a way to download the exact source code of a webpage? I have tried using the URL method and Jsoup method, but I am not getting the precise data as seen in the actual source code. For example: <input type="image" name="ctl00$dtlAlbums$ct ...

Issue with DateTime picker functionality not functioning as expected

My MVC5 project is having trouble with adding a date picker. I keep getting an error in the JS code and I'm not sure what I'm missing. I tried adding Nuget for datetime picker but it's still not working. The console error is: Uncaught TypeE ...

Encountered a "Transformer is not a constructor" error when trying to upgrade the React Native SDK version from 0.61.5 to 0.64

https://i.sstatic.net/LYdxj.pngRecently, I upgraded my react native version to the latest one and encountered an error stating "Transformer is not a constructor". The metro-react-native-babel-preset version I am currently using is 0.64.0. Can someone ple ...

The Google Picker API encounters a server error when attempting to retrieve the OAuth token after being released as a private add-on

Recently, I encountered a puzzling issue with my script that utilizes the Google Picker API. During testing, everything worked flawlessly until I decided to publish it as a private add-on. From that point on, the script's getOAuthToken function starte ...

Guide on implementing OrbitControls to a camera imported from a glTF file

I am facing an issue with OrbitControls.js when trying to apply it to a loaded camera in a three.js scene. While the camera and model load successfully, the OrbitControls.js seem to work only with cameras created directly in the three.js using new THREE.Pe ...

Converting the Python/Flask Backend into a Vue.js Frontend Interface

Recently, I delved into the world of frontend to backend communications. To learn more about this concept, I decided to create a small backend program using the boto3 module in Python to fetch data. The backend program I created is functioning perfectly w ...

Categorize an array by their names using Jquery and present them as a list

I have a list of cities and their corresponding countries structured like the following: { "data": [ { "cityname": "Newyork", "countryname": "USA" }, { "cityname": "amsterdam", "countryname": "Netherland" },{ "cityname": "Washington", "country ...

Tips for customizing video layout using HTML

I currently have a basic video displayed on my website <video width="100%" class="posted_vid"> <source src="uploaded_videos/<?php echo $Video; ?>"> </video> However, the video player appears as a default HTML video, simila ...

Tips for effectively utilizing the overflow:auto property to maintain focus on the final

I am working on a Todo App and facing an issue where the scrollbars don't focus on the bottom of the page when adding a new element. How can this problem be resolved? https://i.stack.imgur.com/IzyUQ.png ...

Looking for a specific item in a two-dimensional array using the C programming language

Looking for some help with a C programming issue I'm facing. I'm new to C programming and struggling to create a string list and search for a specific element. #include <stdio.h> #include <string.h> # define MAX 6 int main(){ ch ...

Utilizing React.js to Sort Through JSON Data

I'm currently working with the following state: constructor(props){ super(props); this.state = { open: false, customers:[], customer:{}, products:[], product:{}, ...