A guide to extracting distinct values from an array of objects by a specified key in Javascript using ES5

This particular post on Stack Overflow discusses a method for retrieving all distinct values from a JavaScript array by eliminating duplicates. One of the answers presents this solution using ES6 syntax, which utilizes arrow functions and spread operators. However, I am seeking assistance in converting this code to ES5 without the use of arrows or ellipses.

var objArr = [{
  id: '123'
}, {
  id: '123'
}, {
  id: '456'
}];

objArr = objArr.reduce(function(acc, cur) {
  return acc.filter(function(obj) {
    return obj.id !== cur.id;
  }).concat(cur);
}, []);

console.log(objArr);

Answer №1

Hopefully this solution proves useful.

const objectArray = [{
  id: '100'
}, {
  id: '200'
}, {
  id: '300'
}];

const newObjectArray = objectArray.reduce((prev, curr) => {
    const exists = prev.filter(item => item.id === curr.id).length > 0;
    if(!exists){
        prev.push(curr);
    }
    return prev;
}, []);

console.log(newObjectArray);

Answer №2

const objectsArr = [{ id: '123' }, { id: '123' }, { id: '456' }]

objectsArr = objectsArr.reduce(function (accumulator, current) {
    return accumulator.filter(function (object) {
        return object.id !== current.id
    }).concat([current])
}, [])

console.log(objectsArr)

Answer №3

To efficiently remove duplicates from an array of objects, you can utilize the reduce method and map function:

let unique = objArr.reduce(function(acc, curr){
    acc[curr.id] = acc[curr.id] || {};
    acc[curr.id] = curr.id;
    return acc;
},{})

console.log(Object.values(unique).map(function(item){return {id: item}}))

Let's consider the following example:

let objArr = [{
  id: '123'
}, {
  id: '123'
}, {
  id: '456'
}];

let unique = objArr.reduce(function(acc, curr){
acc[curr.id] = acc[curr.id] || {};
    acc[curr.id] = curr.id;
return acc;
},{})

console.log(Object.values(unique).map(function(item){return {id: item}}))

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 encountered a couple of unfamiliar error codes while working in Java

I am new to Java and I've been following tutorial videos to learn as I go. However, when I try running the code in Eclipse IDE, it shows 2 errors that I'm currently troubleshooting. import java.util.Arrays; public class Arrays { public sta ...

Yii2 ajax call not redirecting as expected

After clicking a button, I attempted to redirect the user but encountered an issue with the redirection not functioning properly. Below is my JavaScript code for handling the button click event. $('#MyButton').click(function() { $.ajax({ url ...

The efficient Node/Express application, mastering functional programming techniques (Dealing with side-effects in JavaScript)

While there are numerous informative articles discussing the theory of functional programming in JavaScript, few delve into practical examples of how to handle side-effects within a web application. As most real-world applications inevitably involve side-e ...

What is the best method for implementing click functionality to elements that share a common class using only pure JavaScript

I am struggling to figure out how to select specific elements with the same classes using only pure JavaScript (no jQuery). For example: <div class="item"> <div class="divInside"></div> </div> <div class= ...

Having difficulty triggering a button click event in a child iframe using javascript

Experimenting with the Jquery UI dialog has been an interesting experience. I have a web page featuring a gridview, a button for refreshing the gridview, and a link. Clicking on the link opens a dialog window displaying the record details. After making ch ...

socket.io server, management function

var app = require('http').createServer(handler) , io = require('socket.io').listen(app) , fs = require('fs') app.listen(8080); function handler (req, res) { fs.readFile(__dirname + '/index.html', function ( ...

Error encountered when WebDriverIO attempted to connect to Appium due to a lack of compatible capabilities

I'm currently facing an issue while attempting to link my virtual Android Device through Appium with my Webdriverio script for the purpose of automating some testing tasks. Here are the capabilities that I have set: capabilities: [{ // N ...

The concept of Modal being undefined

Upon opening my page, I am attempting to create a modal dialog that displays an image. Strangely, I keep receiving an error stating the image is undefined when trying to display it without using the onclick function. I am working with a modified version of ...

What is the best way to enhance the SQL query limit by activating a button?

I'm new to programming, and I want to learn how to dynamically increase the limit of an SQL query when a button is clicked. Here's what I have so far: <?php $number = 5; $db->query("SELECT * FROM results LIMIT $number"); ?> & ...

Utilizing computed properties to implement table filtering in Vue.js

I am currently working on a table generated from an array of objects in VuE.js and struggling with implementing computed properties for filtering. I need help figuring out the correct way to use filter() within my computed properties to filter the table ba ...

Tips for creating a multi-tenant application using Node.js (express.js)

I need help finding information on developing a multi-tenant application using Node.js. Can anyone offer some guidance? Thank you. My technology stack includes: Node.js Express.js Mocha.js Postgres SQL JavaScript HTML5 ...

Here is a way to attach a function to dynamically generated HTML that is returned in an AJAX request

As I was working on a new function development project, I encountered a situation where I had to add a function to dynamically generated HTML through an ajax call. The following is a snippet of the code: $.ajax( 'success': function(data){ ...

The transformation of a class-based component into a functional one is proving to be ineffective

I am attempting to transform my class-based component into a functional one, but I am struggling with passing two parameters in one onClick function without relying on set state. Additionally, I want to avoid creating multiple extra functions as it would i ...

Advancements in ajax during the simultaneous uploading of multiple files

Hey there, I'm encountering an issue while trying to upload multiple files. The progress bar shows 100% when a small file is uploaded first, then it goes back to the correct percentage for the larger file. How can I ensure that the progress remains ac ...

Holding off on completing a task until the outcomes of two parallel API requests are received

Upon page load, I have two asynchronous API calls that need to be completed before I can calculate the percentage change of their returned values. To ensure both APIs have been called successfully and the total variables are populated, I am currently using ...

What could be causing my MVC Action to not recognize the AJAX object that was passed to it

Despite a successful Ajax call, the passed object appears empty. This involves passing a cart object to a controller action in a straightforward setup. The call goes through, but the object is empty upon reaching the Action. The payload being sent (in C ...

Steps to display the datatable footer on the printed page

I am having trouble understanding the solutions provided for my table query. The current table setup is as follows: <table class="table table-bordered make_datatable"> <thead> <tr> <th>SL No</th> ...

Issue with DropdownListFor validation using jQuery when the onchange event triggers submission

DropdownListFor @Html.DropDownListFor(x => x.selectedDateFilter, new SelectList(Model.bydatefilter, "id", "dt", Model.selectedDateFilter), "--Select Date--", new { onchange = @"this.f ...

Steps to display a variable in JavaScript on an HTML textarea

I'm working on a JavaScript variable called 'signature' var signature; //(Data is here) document.write(signature) Within my HTML document, I have the following: <div id="siggen"> <textarea id="content" cols="80" rows="10">& ...

the final value in a pandas dataframe

In this code snippet, I have successfully accessed the max() value in the array. However, my goal now is to access the last value of the dataframe. How can I accomplish this task? 'horizontal': round(df[['x2', 'x3']].max().max ...