WeSt
WeSt

Reputation: 929

Group array objects

I have a array with objects like this:

[{recordID:'123'},{recordID:'123-opp'},{recordsID:'456'},{recordID:'456-opp'},{recordID:'789'}, {recordID:'980'},...]

So there are some objects with the same recordID just added a -opp and some are single ones and there is no -opp What I want to do is to combine the corresponding objects in a array. and the other one alone in a array. For example:

[[{recordID:'123'},{recordID:'123-opp'}], [{recordID:'456'},{recordID:'456-opp'}],[{recordID:'789'}],[{recordID:'980'}],...]

To mention: sometimes it could be -opp at the end and sometimes -ref.

I tried multiple ways but don't get the right result. This is my Code:

.then(function(dbResult){ //sort and filter the corresponding records
    var records = [];
    var indexToDelete;
    dbResult.forEach(function(item, index){
      var recordPair = dbResult.filter(function(element, i){
        if(element.recordId.includes(item.recordId)){
          indexToDelete = i;
          return true;
        }else{
          return false;
        }
      })
      records.splice(indexToDelete,1);
      records.push(recordPair);
    })
    console.log(records)
    return records;
  })

Maybe someone have even a better solution.

Upvotes: 1

Views: 58

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386746

You could group the result by using a part of the id with a hash table for same groups.

var array = [{ recordID: '123' }, { recordID: '123-opp' }, { recordID: '456' }, { recordID: '456-opp' }, { recordID: '789' }, { recordID: '980' }],
    hash = Object.create(null),
    result = [];

array.forEach(function (o) {
    var key = o.recordID.match(/^\d+/);
    if (!hash[key]) {
        hash[key] = [];
        result.push(hash[key]);
    }
    hash[key].push(o);
});

console.log(result);
console.log(hash);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

marvel308
marvel308

Reputation: 10458

You can do it in the following way

let arr = [{recordID:'123'},{recordID:'123-opp'},{recordID:'456'},{recordID:'456-opp'},{recordID:'789'}, {recordID:'980'}];

let cleanVariable = (str) => +str.replace(/\-opp|\-ref/,'');
let matchVariable = (str1, str2) => cleanVariable(str1) == cleanVariable(str2);
let result = arr.sort((a, b) => cleanVariable(a.recordID) - cleanVariable(b.recordID)).reduce((a, b) => {
    if(a.length == 0) a.push([]);
    if(a[a.length-1].length == 0) a[a.length-1].push(b);
    else if(matchVariable(a[a.length-1][a[a.length-1].length-1].recordID, b.recordID)) a[a.length-1].push(b);
    else a.push([b]);
    return a;
}, []);

console.log(result);

Upvotes: 1

Related Questions