简体   繁体   English

计算和删除嵌套数组中的多个元素

[英]Counting and deleting multiple Elements in a nested Array

this is the structure of my array: 这是我的数组的结构:

arrayParent = [numbers, counter];

numbers = [1,1,1,2,4,5];
counter = [];

what I want to do is counting multiple elements in "numbers" and pushing to "counter" while deleting in the first, in the end it should look like this: 我想做的是在“数字”中计数多个元素,并在第一次删除时将其推到“计数器”,最后看起来应该像这样:

numbers = [1,2,4,5];
counter = [3,1,1,1];

I tried this ( and many many other versions): 我尝试了这个(以及许多其他版本):

for(var y =0; y < arrayParent.length; y++){
 for(var x = 0; x < arrayParent[y].numbers.length; x++){
    var co = 1;
    for(var z = x+1; z < arrayParent[y].numbers.length; z++){
      if(arrayParent[y].numbers[x] == arrayParent[y].ans[z]){
          co++;
          arrayParent[y].numbers.splice(z);
          arrayParent[y].counter[x] = co;
       }
     }
   }
}

The result I got: 我得到的结果是:

numbers = [1,2,4,5];
counter = [3,,,];

Any ideas how to solve? 任何想法如何解决?

you can try something like: 您可以尝试类似:

 let numbers = [1,1,1,2,4,5]; let counter = []; const tmp = numbers.reduce((res, curr) => ({ ...res, [curr]: (res[curr] || 0) + 1 }), {}); numbers = Object.keys(tmp).map(Number); counter = Object.values(tmp); console.log(numbers, counter); 

so, I created a counter object where keys are distinct numbers and values are their counter 因此,我创建了一个计数器对象,其中键是不同的数字,值是它们的计数器

As @nikhil correctly noticed this method will not preserve numbers order, to preserve it, just change JS object to JS Map, the logic is the same: 正如@nikhil正确地注意到,此方法不会保留数字顺序,要保留它,只需将JS对象更改为JS Map,其逻辑是相同的:

 let numbers = [1,1,1,2,5, 4]; let counter = []; const tmp = numbers.reduce((res, curr) => res.set(curr, (res.get(curr) || 0) + 1), new Map()); numbers = [...tmp.keys()]; counter = [...tmp.values()]; console.log(numbers, counter); 

You can try following 您可以尝试关注

 let arrayParent = {numbers : [1,1,1,2,4,5], counter : []}; // This will ensure that the order of elements is same as in the array let order = []; // Create an object with key as `number` and counts as its value let map = arrayParent.numbers.reduce((a,c) => { if(a[c]) a[c]++; else {a[c] = 1; order.push(c); } return a; }, new Map()); // Set the value of order in numbers arrayParent.numbers = order; // Set the counts in counter order.forEach(o => arrayParent.counter.push(map[o])); console.log(arrayParent); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM