1

Given we have and array of objects:

let objects = [
  {name: 'bob'},
  {name: 'foo'},
  {name: 'bar'},
  {name: 'foo'},
  {name: 'foo'}
]

How can i transform this array to this one:

let objects = [
  [
    {name: 'bob'}
  ],
  [
    {name: 'foo'},
    {name: 'foo'},
    {name: 'foo'}
  ],
  [
    {name: 'bar'}
  ]
]

Higher order functions

0

2 Answers 2

2

You could use the array .reduce() method to iterate over the array and put each object into an array in a working object keyed off the name property, then afterwards use Object.values() to convert that working object into an array of arrays:

let objects = [
  {name: 'bob'},
  {name: 'foo'},
  {name: 'bar'},
  {name: 'foo'},
  {name: 'foo'}
]

let result = Object.values(objects.reduce((a,c) => {
  if (!a[c.name]) a[c.name] = []
  a[c.name].push(c)
  return a
}, {}))

console.log(result)

Sign up to request clarification or add additional context in comments.

1 Comment

Way prettier than mine XD
1

let objects = [{
    name: 'bob'
  },
  {
    name: 'foo'
  },
  {
    name: 'bar'
  },
  {
    name: 'foo'
  },
  {
    name: 'foo'
  }
]
let result = objects.reduce((accumulator, currentValue) => {
  if (!Array.isArray(accumulator)) {
    //console.log("once")
    var temp = accumulator;
    accumulator = [
      [],
      [],
      []
    ];
    accumulator[0].push(temp)
    return accumulator;
  }
  
 

  for(var i = 0; i < accumulator.length;i++){
  //console.log(accumulator[i][0],currentValue.name)

    if(accumulator[i][0] == undefined){
    //console.log("was undefined")
      accumulator[i] =[currentValue]
      return accumulator;
    }else if(accumulator[i][0].name == currentValue.name){
      //console.log("found match")
      accumulator[i].push(currentValue)
      return accumulator;
    }  
  }



  return accumulator;
});

console.log(result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.