Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding unique objects in array

I have an array as follows:

const arr = [
            {company: 'a', date: '1'},
            {company: 'b', date: '1'},
            {company: 'c', date: '1'},
            {company: 'a', date: '2'},
            {company: 'a', date: '1'},
            {company: 'b', date: '2'},
          ]

I just want to know how to get the unique objects inside it. I tried using lodash with this command:

uniqBy(arr, 'date');

But it only returns:

[
  {company: "a", date: "1"},
  {company: "a", date: "2"}
]

I want something like this one:

[
  {company: "a", date: "1"},
  {company: "a", date: "2"},
  {company: "b", date: "1"},
  {company: "b", date: "2"},
  {company: "c", date: "1"},
]

Is there a way in lodash or vanilla JS to have this done?

like image 881
Noel Rosales Avatar asked Jan 27 '20 16:01

Noel Rosales


1 Answers

With help of reduce() in pure js you I created a function which takes an array of objects and array of keys as inputs and return the array which is unique by all those keys.

Following are the steps of the algorithm:

  • First we need to create an object using reduce().
  • The key of that object will be the values of required keys which are provided each joined by -(I mentioned keyString for each object in the comment of code).
  • The object which will have same keyString means same values for given array of keys will automatically occur only once because object can't have duplicate keys
  • At last we use Object.values() to to create an array.

const arr = [
            {company: 'a', date: '1'}, //keyString = "a-1"
            {company: 'b', date: '1'}, //keyString = "b-1"
            {company: 'c', date: '1'}, //keyString = "c-1"
            {company: 'a', date: '2'}, //keyString = "a-2"
            {company: 'a', date: '1'}, //keyString = "a-1"
            {company: 'b', date: '2'}, //keyString = "b-2"
            //The item at index 0 and index 4 have same keyString so only a single of them will remain in object.
          ] 

const uniqueBy = (arr, keys) => {
  const obj = arr.reduce((ac, a) => {
    let keyString = keys.map(k => a[k]).join('-');
    ac[keyString] = a;
    return ac;
  }, {});
  return Object.values(obj);
}

console.log(uniqueBy(arr, ['company', 'date']))
like image 198
Maheer Ali Avatar answered Oct 08 '22 03:10

Maheer Ali