-1

Say I have this:

var arr = [
    {type:"orange", title:"First"},
    {type:"orange", title:"Second"},
    {type:"banana", title:"Third"},
    {type:"banana", title:"Fourth"}
];

And I'd like to get to this.

[[{type:"orange", title:"First"},
{type:"orange", title:"Second"}],

[{type:"banana", title:"Third"},
{type:"banana", title:"Fourth"}]]

I've seen a lot for getting to this:

{orange: 
[[{type:"orange", title:"First"},
{type:"orange", title:"Second"}], 
banana: 
[{type:"banana", title:"Third"},
{type:"banana", title:"Fourth"}]}

But it doesn't help my situation, I need it to be arrays inside an array. Any help will be greatly appreciated

profiter
  • 45
  • 5

2 Answers2

2

With one more step, you can map it to the format you want.

var arr = [
    {type:"orange", title:"First"},
    {type:"orange", title:"Second"},
    {type:"banana", title:"Third"},
    {type:"banana", title:"Fourth"}
];


const typeDictionary = {}

for (item of arr) {
  if (!typeDictionary[item.type]) {
    typeDictionary[item.type] = [item]
  } else {
    typeDictionary[item.type].push(item)
  }
}

// This is the final missing step
const finalResult = Object.values(typeDictionary)

console.log('finalResult', finalResult)

finalResult [
  [
    { type: 'orange', title: 'First' },
    { type: 'orange', title: 'Second' }
  ],
  [
    { type: 'banana', title: 'Third' },
    { type: 'banana', title: 'Fourth' }
  ]
]
JBaczuk
  • 13,886
  • 10
  • 58
  • 86
0

You could use this strategy

  • Find all the unique types, ['orange','banana']
  • For each unique type Array#filter the original array
  • DONE

const input = [
    {type:"orange", title:"First"},
    {type:"orange", title:"Second"},
    {type:"banana", title:"Third"},
    {type:"banana", title:"Fourth"}
];

const output = [...new Set(input.map(o => o.type))]
    .map( type => input.filter(o => o.type === type) )

console.log( output );

Alternatively, you could use Array#reduce as follows:

const input = [
    {type:"orange", title:"First"},
    {type:"orange", title:"Second"},
    {type:"banana", title:"Third"},
    {type:"banana", title:"Fourth"}
];

const output = input.reduce((prev, {type,title}) => {
    let x = prev.findIndex(ar => ar[0].type === type);
    if( x > -1 ) {
        prev[x].push({type,title});
    } else {
        prev.push([{type,title}])
    }
    return prev;
}, []);
    

console.log( output );
PeterKA
  • 24,158
  • 5
  • 26
  • 48
  • This is far less efficient than a standard group-by (O(n*m) vs O(n)), and also this question is a duplicate multiple times over. – pilchard Apr 06 '22 at 20:46