GoodCat
GoodCat

Reputation: 117

Breaking a single array into many arrays based on values within array. JavaScript

This is a continuation from a previous question in regards to grouping. I have a file of structure below and what I want to do rather than simply isolating one id I want to loop through the entire array (imagine 1000+ ids) and create separate arrays for each which I can then do further work on. So in the example below id1 would be group together in one array and id2 would be grouped together in another array. Once I had separated each ID into a separate array I would then continue to filter each further based on a set of conditions.

[{col1: 'id1', col2: '123', col3: '12/01/12'},
{col1: 'id1', col2: '100', col3: '12/01/12'},
{col1: 'id2', col2: '-100', col3: '12/01/12'},
{col1: 'id2', col2: '123', col3: '13/01/12'}]

.

Any advice on the best way to break the array down and then how to call individual ID arrays would be much appreciated.

Thanks in advance

Upvotes: 1

Views: 58

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386570

You could use the given id as key for an object and collect the items in own array.

var data = [{ col1: 'id1', col2: '123', col3: '12/01/12' }, { col1: 'id1', col2: '100', col3: '12/01/12' }, { col1: 'id2', col2: '-100', col3: '12/01/12' }, { col1: 'id2', col2: '123', col3: '13/01/12' }],
    object = data.reduce(function (r, o) {
        r[o.col1] = r[o.col1] || [];
        r[o.col1].push(o);
        return r;
    }, Object.create(null));
    
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 3

vinayakj
vinayakj

Reputation: 5681

If you want to have the array of arrays of same ids grouped together, try below code.

var a  = [{col1: 'id1', col2: '123', col3: '12/01/12'},
{col1: 'id1', col2: '100', col3: '12/01/12'},
{col1: 'id2', col2: '-100', col3: '12/01/12'},
{col1: 'id2', col2: '123', col3: '13/01/12'}];
var currentID = a[0].col1;
var group = [];
var collectionOfIDs = [];
a.forEach(function(v, i) {
  //console.log(i,v);
  if (currentID == v.col1) {
    collectionOfIDs.push(v);
  } else {
    group.push(collectionOfIDs);
    currentID = v.col1;
    collectionOfIDs = [v];
  }
});
group.push(collectionOfIDs);
console.log(group)

Upvotes: 1

Related Questions