Javascript - 如何增加唯一键的值

Javascript - how to increment values on unique keys

我正在尝试使用唯一键和分配的增量值创建一个数组,以便最终得到一个加权列表。

PHP中,我是这样做的...

$crit1 = ['a','b','c'];
$crit2 = ['c','d','e'];
$weight = [];
foreach ( $crit1 as $item ) {$weight[$item] += 1;}
foreach ( $crit2 as $item ) {$weight[$item] += 2;}   
// print_r($weight); => array([a] => 1 [b] => 1 [c] => 3 [d] => 2 [e] => 2)

...'c' 获得最高分:1 分出现在第一个 foreach 中,另外 2 分出现在第二个 foreach 中。

正在尝试将其翻译成 JS...

const crit1 = ['a','b','c'];
const crit2 = ['c','d','e'];
let weight = [];   
crit1.forEach(function (item) { weight.push({ [item]: +1 }) });
crit2.forEach(function (item) { weight.push({ [item]: +2 }) });
// console.log(weight) => [{ a: 1}, { b: 1}, { c: 1}, { c: 2}, { d: 2}, { e: 2}]

...不再有效 - 'c' 的值是单独分配的,因此数组有 6 个项目而不是只有 5 个。

我做错了什么?

  1. 使用 object 而不是数组,这样键的值就可以增加

  2. 由于我们使用的是一个对象,所以我们不能使用push,但是我们需要解决key

  3. weight[item] = (weight[item] || 0) + 1)
    

    weight 对象中的当前 item 键递增 1,如果尚未定义,我们将其设置为 0

const crit1 = ['a','b','c'];
const crit2 = ['c','d','e'];
let weight = {};   

crit1.forEach((item) => weight[item] = (weight[item] || 0) + 1);
crit2.forEach((item) => weight[item] = (weight[item] || 0) + 2);

let arr = Object.keys(weight).reduce((prev, cur) => [ ...prev, { [cur]: weight[cur] } ], []);

console.log(weight);
console.log(arr);

{
  "a": 1,
  "b": 1,
  "c": 3,
  "d": 2,
  "e": 2
}

如果你真的想要一个包含只有一个键的对象的数组,如, we can use reduce()所示进行转换:

let arr = Object.keys(weight).reduce((prev, cur) => [ ...prev, { [cur]: weight[cur] } ], []);

将产生:

[
  {
    "a": 1
  },
  {
    "b": 1
  },
  {
    "c": 3
  },
  {
    "d": 2
  },
  {
    "e": 2
  }
]