将JavaScript数组中的相同值分组

时间:2018-12-04 13:30:10

标签: javascript arrays dictionary filter reduce

let array = ['a', 'a', 'a', 'b', 'b', 'c'];

我想对数组中的双精度值进行分组,以获得如下结果:

结果: ['3a, 2b, c']
(或类似的东西)

有什么主意吗?

6 个答案:

答案 0 :(得分:2)

您可以使用.reduce().map()方法:

let array = ['a', 'a', 'a', 'b', 'b', 'c'];

let result = Object.entries(
    array.reduce((r, c) => (r[c] = (r[c] || 0) + 1, r) , {})
).map(([k, v]) => v == 1 ? k : v + k);

console.log(result);

如果您需要按特定顺序排列商品,也可以使用Map

let array = ['a', 'a', 'a', 'b', 'b', 'c'];

let result = (((arr, map) => {
    arr.forEach(s => map.set(s, (map.get(s) || 0) + 1));
    return [...map.entries()].map(([k, v]) => v == 1 ? k : v + k);
})(array, new Map()));

console.log(result);

答案 1 :(得分:1)

function count() {
array_elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
array_elements.sort();
var current_elements = null;
var count= 0;
for (var i = 0; i < array_elements.length; i++) {
    if (array_elements[i] != current_elements) {
        if (cnt > 0) {
            console.log(current_elements+count);
        }
        current_elements= array_elements[i];
        count= 1;
    } else {
        count++;
    }
}
if (cnt > 0) {
    console.log(current_elements+count);
}

}

答案 2 :(得分:1)

用于简单run-length encoding (RLE)函数的单循环方法。

let array = ['a', 'a', 'a', 'b', 'b', 'c'],
    result = array.reduce(
        (r, c, i, a) => r.concat(c === a[i - 1]
            ? ((+r.pop().slice(0, -1) || 1) + 1) + c
            : c),
        []
    );

console.log(result);

答案 3 :(得分:0)

我建议使用字典来跟踪数组中的重复值。

var dictionary = {};
for(var i = 0;i < array.length;i++){
   var value = array[i];
   if(dictionary[value] === undefined){
      dictionary[value] = 0;
   }
   dictionary[value] = dictionary[value] + 1;

}
console.log(dictionary)

答案 4 :(得分:0)

您可以使用Array.reduce()来生成具有键-值(数组值和计数)对的对象,然后使用Array.map()使用Object.keys()来生成数组。

let array = ['a', 'a', 'a', 'b', 'b', 'c'];

let countObj = array.reduce((acc, val) => (acc[val] = acc[val] ? acc[val] + 1 : 1, acc), {});

console.log(countObj);

let countArr = Object.keys(countObj).map(key => '' + countObj[key] + key);

console.log(countArr);

答案 5 :(得分:0)

对于“类似的东西”,为什么不仅仅拥有一个将字母映射到出现的对象。然后,您可以简单地使用点表示法来获取分配给每个键的属性值。

这里我用过reduce

const arr = ['a', 'a', 'a', 'b', 'b', 'c'];

// `reduce` over the arr
const obj = arr.reduce((acc, c) => {

  // If the object (acc) we passed in doesn't have
  // a key assigned to the letter in the current
  // iteration (c) add it, set it to 0, then
  // add one, otherwise, if there is a key, add one
  acc[c] = (acc[c] || 0) + 1;

  // Return the object for the next iteration
  return acc;

// Pass in an initial object 
}, {});

console.log(obj);

// Grab the value of `a` property
console.log(obj.a);