How can I get a unique array based on object property using underscore

Viewed 57164

I have an array of objects and I want to get a new array from it that is unique based only on a single property, is there a simple way to achieve this?

Eg.

[ { id: 1, name: 'bob' }, { id: 1, name: 'bill' }, { id: 1, name: 'bill' } ]

Would result in 2 objects with name = bill removed once.

8 Answers

A better and quick approach

var table = [
  {
    a:1,
    b:2
  },
  {
    a:2,
    b:3
  },
  {
    a:1,
    b:4
  }
];

let result = [...new Set(table.map(item => item.a))];
document.write(JSON.stringify(result));

Found here

I was looking for a solution which didn't require a library, and put this together, so I thought I'd add it here. It may not be ideal, or working in all situations, but it's doing what I require, so could potentially help someone else:

const uniqueBy = (items, reducer, dupeCheck = [], currentResults = []) => {
  if (!items || items.length === 0) return currentResults;
  
  const thisValue = reducer(items[0]);
  
  const resultsToPass = dupeCheck.indexOf(thisValue) === -1 ?
    [...currentResults, items[0]] : currentResults;
    
  return uniqueBy(
    items.slice(1),
    reducer,
    [...dupeCheck, thisValue],
    resultsToPass,
  );    
}

const testData = [
  {text: 'hello', image: 'yes'},
  {text: 'he'},
  {text: 'hello'},
  {text: 'hell'},
  {text: 'hello'},
  {text: 'hellop'},
];

const results = uniqueBy(
  testData,
  item => {
    return item.text
  },
)

console.dir(results)

unique array by id property with ES6:

arr.filter((a, i) => arr.findIndex(b => b.id === a.id) === i);  // unique by id

replace b.id === a.id with the relevant comparison for your case

Related