Kevin
Kevin

Reputation: 17

How to get unique values from a object array based on a key field utilizing Javascript with ES5

In this post Get all unique values in a JavaScript array (remove duplicates) one of the answers shows how to get unique items for an object array based on a value of a field (shown below), but it is in ES6 notation and I need help converting it to ES5 (no arrows or elipses).

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

objArr = objArr.reduce((acc, cur) => [
  ...acc.filter((obj) => obj.id !== cur.id), cur
], []);

console.log(objArr);

Upvotes: 0

Views: 705

Answers (3)

StepUp
StepUp

Reputation: 38114

You can use reduce method and map function:

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

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

An example:

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

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

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

Upvotes: 0

Ben Aston
Ben Aston

Reputation: 55729

let 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)

Upvotes: 2

Mauricio
Mauricio

Reputation: 84

i hope this help

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

var newObjArr = objArr.reduce(function(previous, current){
    var alredyExists = previous.filter(function(item){
        return item.id === current.id
    }).length > 0
    if(!alredyExists){
        previous.push(current)
    }
    return previous
}, [])

console.log(newObjArr)

Upvotes: 2

Related Questions