对象中的错误计数以及在对象和数组之间对相同值进行计数的正确方法

时间:2019-01-19 02:00:06

标签: javascript arrays json object duplicates

我试图在对象和数组中计数相同的值,并且应该显示数组中显示的第一个数字以在对象中显示它 这是我的错误代码和示例案例:

let index = {};
let result = [];
const arrayList = [{
  "code": 101,
  "name": "banana",
  "price": 1000
}, {
  "code": 4,
  "name": "bluebberries",
  "price": 3000
}, {
  "code": 900,
  "name": "apple",
  "price": 300
}];
 
  // here is value of code in object list
const userChoose = [900, 900, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101];




userChoose.forEach(ar => {
  arrayList.forEach(point => {
    let key = ar;
    if (key in index) {
      index[key].count++;
    } else {
      let newEntry = {
        id: point.code,
        count: 1
      };
      index[key] = newEntry;
      result.push(newEntry);
    }

  })
});
console.log(result);

输出与我想要的不一样:

// final result:
[
  {
    "id": 900,
    "count": 2
  },
  {
    "id": 101,
    "count": 11
  }
]

1 个答案:

答案 0 :(得分:0)

我认为这就是您想要的。

let index = {};
let result = [];
const arrayList = [{
  "code": 101,
  "name": "banana",
  "price": 1000
}, {
  "code": 4,
  "name": "bluebberries",
  "price": 3000
}, {
  "code": 900,
  "name": "apple",
  "price": 300
}];
 
  // here is value of code in object list
const userChoose = [900, 900, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101];


userChoose.forEach(item => {
  if(result.some(i => i.id === item) === false) {
    let obj = arrayList.find(e => e.id === item);

    result.push({ 
      id: item,
      count: 0
    });
  }
  result.find(r => r.id === item).count++;
});

console.log(result);