0

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);
Kevin
  • 17
  • 5

3 Answers3

2

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)
Mauricio
  • 84
  • 1
  • 8
2

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)
Ben Aston
  • 53,718
  • 65
  • 205
  • 331
0

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}}))
StepUp
  • 36,391
  • 15
  • 88
  • 148