组数组对象

我有一个像这样的对象的数组:

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

所以有一些对象具有相同的recordID只是添加了一个-opp ,有些是单一的,没有-opp我想要做的是将相应的对象组合在一个数组中。 另一个单独在一个arrays中。 例如:

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

提一下:有时候可能会在结尾处有-opp ,有时候-ref

我尝试了多种方式,但没有得到正确的结果。 这是我的代码:

 .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; }) 

也许有人有更好的解决scheme。

您可以通过将相同组的哈希表的id的一部分用于相同的组,从而对结果进行分组。

 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; } 

你可以通过以下方式来完成

 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);