我有以下数组,我期待检索元素正在改变的原始(已排序)数组的索引以及单个元素存在的频率。
ab = [1,1,1,3,3,5,5,5,5,5,6,6]
期望的结果应该是这样的:
ac = [0,3,5,10]
ad = [3,2,5,2]
非常感谢您的任何建议。
干杯。
您可以迭代数组并检查前一个。如果相等,则递增最后一次计数,否则添加索引和计数一次。
var array = [1, 1, 1, 3, 3, 5, 5, 5, 5, 5, 6, 6],
{ indices, counts } = array.reduce((r, v, i, a) => {
if (a[i - 1] === v) {
r.counts[r.counts.length - 1]++;
} else {
r.indices.push(i);
r.counts.push(1);
}
return r;
}, { indices: [], counts: [] });
console.log(...indices);
console.log(...counts);
此代码生成与您发布的输出类似的输出:
var ab = [1,1,1,3,3,5,5,5,5,5,6,6];
var ac = Array.from(new Set(ab.map((e) => ab.indexOf(e))));
var ad = [];
for (var i = 0; i < ac.length - 1; i++) {
ad.push(ac[i + 1] - ac[i]);
}
ad.push(ab.length - ac[ac.length - 1]);
console.log(...ab);
console.log(...ac);
console.log(...ad);
试试这个,应该得到你想要的
ab = [1,1,1,3,3,5,5,5,5,5,6,6];
var items = [];
var positions = [];
var count = [];
ab.map((item, index)=>{
//check if exist
let item_index = items.indexOf(item);
if(item_index == -1) {
items.push(item);
positions.push(index);
count.push(1);
} else {
let current_count = count[item_index];
count[item_index] = ++current_count;
}
});
console.log(positions);
console.log(count);
所以,使用https://underscorejs.org/#groupBy你可以按值分组
_.groupBy([1,1,1,3,3,5,5,5,5,5,6,6]);
or
_.groupBy([1,1,1,3,3,5,5,5,5,5,6,6], function(num){ return num; })
你会得到一个像这样的物体
{1: [1,1,1], 3: [3,3], 5: [5,5,5,5,5], 6: [6,6]}
因此,如果你采取所有https://underscorejs.org/#keys并迭代,键下的值是数组,取大小并附加到新数组,所以你可以使ad = [3,2,5,2]
再次,遍历键并获得https://underscorejs.org/#indexOf,你可以构造ac = [0,3,5,10]
玩这些方法,检查示例,你可以自己做!