Javascript - 计算相同值并将相同值的结果除以数组

Javascript - Count same values and divide result of same values in array

下面代码中如何使用除法运算

这里我使用条件如果数组值1是红色,2是白色,3是棕色

因为这是一只袜子,所以如果值等于 2 则它被算作一对 (1)。

const stok = [1,1,2,2,3,3,3,3];

function sockMerchant() {
    const colors = ["","red","white","brown"]; 
    const count = stok => stok.reduce((prev, curr) => (prev[curr] = ++prev[curr] || 1, prev), {}); 
    
    const strings = Object.entries(count(stok)).reduce((acc,[key,val]) => (acc[colors[key]] = val , acc),[]); 

    return strings;
    
}



console.log(sockMerchant(stok))

如果有相同的值并且计算出的值是偶数则除以2

我的输出

[red: 2, white: 2, brown: 4]

我的预期输出

[red: 1, white: 1, brown: 2]

**提前致谢

您无法获取具有属性的数组。

所以,我正在创建一个具有问题要求的对象。

const stok = [1, 1, 2, 2, 3, 3, 3, 3];

function sockMerchant() {
  const colors = ["red", "white", "brown"];
  const count = stok.reduce((prev, curr) => {
    prev[curr - 1]++; //add to the index in prev
    return prev;
  }, [...Array(colors.length)].fill(0));
  //take an array initially with the length of colors and value 0

  const obj = {};
  colors.forEach((a, i) => {
    obj[a] = Math.floor(count[i] / 2); //you can use ceil if u want to count single left over as 1
  })

  return obj;

}



console.log(sockMerchant(stok))