Search code examples
javascriptarraysobjectunique-key

Get all unique values from objects and assign them into array under correct key


I have an array of objects to be converted to an object with an array of unique values assigned to the same keys.

How can I get this output?

//input

let users = [
  { id: 1, name: "Alan", surname: "Davis", age: 34, isAdmin: 'yes'},
  { id: 2, name: "John", surname: "Doe", age: 35, isAdmin: 'no'},
  { id: 3, name: "Monica", surname: "Bush", age: 25, isAdmin: 'no'},
  { id: 4, name: "Sandra", surname: "Back", age: 23, isAdmin: 'no'},
  { id: 5, name: "Jacob", surname: "Front", age: 34, isAdmin: 'yes'},
];

//output

let unique = {
  id: [1, 2, 3 ,4 ,5],
  name: ['Alan', 'John', 'Monica', 'Sandra', 'Jacob'],
  surname: ['Davis', 'Doe', 'Bush', 'Back', 'Front'],
  age: [34, 35, 25, 23],
  isAdmin: ['yes', 'no'],
}

Solution

  • You can use Array.prototype.reduce() and for all of the items iterate over with Array.prototype.forEach() and creating a unique array with Set

    Code:

    const users = [{ id: 1, name: 'Alan', surname: 'Davis', age: 34, isAdmin: 'yes' },{ id: 2, name: 'John', surname: 'Doe', age: 35, isAdmin: 'no' },{ id: 3, name: 'Monica', surname: 'Bush', age: 25, isAdmin: 'no' },{ id: 4, name: 'Sandra', surname: 'Back', age: 23, isAdmin: 'no' },{ id: 5, name: 'Jacob', surname: 'Front', age: 34, isAdmin: 'yes' },]
    
    const unique = users.reduce((a, c) => (
      Object
        .entries(c)
        .forEach(([k, v]) => a[k] = [...new Set([...(a[k] || []), v])]), 
      a
    ), {})
    
    console.log(unique)