在Javascript中,我试图采取数字值的初始数组,并计算其中的元素。理想情况下,结果将是两个新数组,第一个数组指定每个唯一元素,第二个数组包含每个元素出现的次数。但是,我愿意听取关于输出格式的建议。

例如,如果初始数组是:

5, 5, 5, 2, 2, 2, 2, 2, 9, 4

然后将创建两个新数组。第一个将包含每个唯一元素的名称:

5, 2, 9, 4

第二个将包含该元素在初始数组中出现的次数:

3, 5, 1, 1

因为数字5在初始数组中出现了三次,数字2出现了五次,9和4都出现了一次。

我一直在寻找解决方案,但似乎没有一个可行,而且我自己尝试过的每件事最后都出奇地复杂。任何帮助都将不胜感激!

谢谢:)


当前回答

似乎问题特别要求有两个结果数组,我还没有看到,所以这是我的解决方案:

const theArray = [1, 3425, 56, 7, 9, 5, 4, 3425, 7, 7, 7];

const uniqueVals = [...new Set(theArray)];
const countPerUniqueValArray = uniqueVals.map(uv => theArray.filter(i => i === uv).length);

console.log(uniqueVals);
console.log(countPerUniqueValArray);

// Expect:
// [1, 3425, 56, 7, 9, 5, 4]
// [1, 2, 1, 4, 1, 1, 1]

其他回答

您可以通过使用count函数扩展数组来简化这一点。它的工作原理类似于Ruby的array# count,如果你熟悉它的话。

Array.prototype.count = function(obj){
  var count = this.length;
  if(typeof(obj) !== "undefined"){
    var array = this.slice(0), count = 0; // clone array and reset count
    for(i = 0; i < array.length; i++){
      if(array[i] == obj){ count++ }
    }
  }
  return count;
}

用法:

let array = ['a', 'b', 'd', 'a', 'c'];
array.count('a'); // => 2
array.count('b'); // => 1
array.count('e'); // => 0
array.count(); // => 5

Gist


Edit

然后你可以使用array# filter获取你的第一个数组,包含每个出现的项:

let occurred = [];
array.filter(function(item) {
  if (!occurred.includes(item)) {
    occurred.push(item);
    return true;
  }
}); // => ["a", "b", "d", "c"]

你的第二个数组,使用数组#count到数组#map:

occurred.map(array.count.bind(array)); // => [2, 1, 1, 1]

或者,如果顺序无关紧要,你可以直接返回一个键值对:

let occurrences = {}
occurred.forEach(function(item) { occurrences[item] = array.count(item) });
occurences; // => {2: 5, 4: 1, 5: 3, 9: 1}

不要使用两个数组的结果,使用一个对象:

a      = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
result = { };
for(var i = 0; i < a.length; ++i) {
    if(!result[a[i]])
        result[a[i]] = 0;
    ++result[a[i]];
}

然后结果将看起来像:

{
    2: 5,
    4: 1,
    5: 3,
    9: 1
}
function countOcurrences(arr){
    return arr.reduce((aggregator, value, index, array) => {
      if(!aggregator[value]){
        return aggregator = {...aggregator, [value]: 1};  
      }else{
        return aggregator = {...aggregator, [value]:++aggregator[value]};
      }
    }, {})
}

根据@adamse和@pmandell的回答(我支持),在ES6中,你可以在一行中完成:

2017年编辑:我使用||来减少代码大小,使其更具可读性。

var =[7, 1、7、2、2、7、3、3、3、7、7、7、7]; 警报(JSON.stringify ( a.reduce ((r, k) = > {[k] = 1 + r [k] | | 1;返回r}, {}) ));


它可以用来计数字符:

var s =“唵嘛呢叭咪吽”; 警报(JSON.stringify ( s.split(”)。Reduce ((a, c)=>{a[c]++?0:a[c]=1;返回a},{}) ));

Const data = [5,5,5,2,2,2,2,2,2,2,2,9,4] 函数计数(arr) { 加勒比海盗。减少((上一页,咕咕叫)= >(上一页[咕咕叫]= + +上一页[咕咕叫]| | 1,上一页),{}) } console.log (count(数据)