根据它的键对数组进行分组,并创建一个包含组的新数组作为其索引

时间:2018-03-29 14:22:26

标签: javascript arrays

我正在尝试从一个数组创建一个新数组,该数组将按键分组,新数组的索引将是旧数组的键,如下所示

旧数组

Array1
0 :term_id: "1"
   capacity:"11"
   price: "452"
1 :term_id: "2"
   capacity:"33"
   price: "44"
2 :term_id: "1"
   capacity:"1"
   price: "2"

我希望按term_id对此数组进行分组,以便新数组

新数组

Array2
1 :terms >
   0: capacity:"11"
      price: "452"
   1: capacity:"1"
      price: "2"
2 :terms >
  0:  capacity:"33"
      price: "44"

正如您所看到的,在新数组中,数组按term_id的索引分组,内部还有另一个内容及其内容

我尝试使用groupBy方法,但我无法保留旧数组的索引

5 个答案:

答案 0 :(得分:1)

您可以使用函数webHttpBinding对所需的输出进行分组和构建。



reduce

var Array1 = [{  term_id: "1",  capacity: "11",  price: "452"}, {  term_id: "2",  capacity: "33",  price: "44"}, {  term_id: "1",  capacity: "1",  price: "2"}];

var result = Object.values(Array1.reduce((a, {term_id, capacity, price}) => {
  (a[term_id] || (a[term_id] = {terms: []})).terms.push({capacity, price});
  return a;
}, {}));

console.log(result);




答案 1 :(得分:1)

您可以使用Paragraph 1 根据对象中的array#reduce对对象数组进行分组,然后使用term_id获取所有值。



Object.values()




答案 2 :(得分:1)

您可以使用Array.prototype的reduce

x = [{term_id:"1",capacity:"11",price:"452"},{term_id:"2",capacity:"33",price:"44"},{term_id:"1",capacity:"1",price:"2"}];

y = x.reduce((n, e) => {
            var clone = Object.assign({}, e);  //creating duplicate object
            delete clone.term_id;              //deleteing term_id property from clone object
            if (!n[e.term_id]) {
                n[e.term_id] = [];
            }
            n[e.term_id].push(clone);    //pushing clone instead of e as e contains term_id which we don't need in result
            return n;
        }, {});
   
console.log(y);

答案 3 :(得分:0)

只需使用哈希表进行分组:

 const result = [], hash = {};

 for(const obj of array) {
   if(hash[obj.term_id]) {
     hash[obj.term_id].push(obj);
   } else {
     result.push(hash[obj.term_id] = [obj]);
   }
 }

答案 4 :(得分:0)

如果您想使用循环...将所有数据复制到结果中会浪费内存,我认为生成所需数据并保留已存在的任何值都是更好的做法,但这可能导致更加丑陋的代码,所以-_-

function idxOfGroupBy(hl,key){
let ret = [];
for(var k = 0; k < hl.length; k++){
	try{
		ret[hl[k][key]].push(k);
	}catch(err){
		ret[hl[k][key]] = [];
		ret[hl[k][key]].push(k);
	}
}
return(ret);
}

let hashList = [{at1:"1",atr2:"."},{at1:"2",atr2:".."},{at1:"1",atr2:"..."}];
let groupIdxs = idxOfGroupBy(hashList,"at1");
console.log(groupIdxs);