如何检查数组中是否有相等的值

时间:2018-09-28 07:56:48

标签: javascript jquery arrays json

我有一系列产品,可以循环播放并将它们显示在商品上。但是,可能会发生同一天多次选择同一产品的情况,因此我希望正确显示数量,但是我不确定该怎么做。

所以我的数组看起来像这样:

[
  {product_id: "679", quantity: "1", chosen_date: "2018-10-01"}
  {product_id: "675", quantity: "1", chosen_date: "2018-10-02"}
  {product_id: "675", quantity: "1", chosen_date: "2018-10-02"}
  {product_id: "675", quantity: "1", chosen_date: "2018-10-03"}
]

这是显示每个项目的循环

let elementWrapper = document.querySelectorAll('.items') 
for (var i = 0; i < items.length; i++){
    let elem = elementWrapper[i];
    let chosen_date = items[i].chosen_date;
    let product_id = items[i].product_id;
    let quantity = items[i].quantity;
    let span = document.createElement('span');
    span.innerHTML = moment(chosen_date).locale('da').format('Do MMM');
    elementWrapper[i].append(span);
}

其中“ items”是数组。

像上面提到的,我希望将ID为“ 675”的产品(其数量是“ 2018-10-02”的两倍)仅显示一次,数量为2

我该如何实现?

1 个答案:

答案 0 :(得分:0)

var items = [
  {product_id: "679", quantity: 1, chosen_date: "2018-10-01",another:'a'},
  {product_id: "675", quantity: 1, chosen_date: "2018-10-02",another:'b'},
  {product_id: "675", quantity: 1, chosen_date: "2018-10-02",another:'a'},
  {product_id: "675", quantity: 1, chosen_date: "2018-10-03",another:'c'}
];

var incrementField = 'quantity';
var exceptFields = ['another'];
/**
* @param items [array] items as a multidimensional array
* @param incrementField [string]
* @param exceptFields [array]
**/
function plusArrays(items,incrementField,exceptFields=[]){
  // array with a filtered keys and values to help searching
  unique_arrays = [];
  // Original arrays
  unique_arrays_without_except = [];
  items.forEach(function(item){
    // Cloning the item
    original_item = JSON.parse(JSON.stringify(item));
    // Deleting the excep fields
    exceptFields.forEach(function(except){
      delete item[except];
    })
    // Getting the increment value before delting it
    var incrementValue = item[incrementField];
    // unsetting the incrementValue property
    delete item[incrementField];
    // Adding the increment value
    if(unique_arrays.indexOf(JSON.stringify(item))+1>0) {
  unique_arrays_without_except[unique_arrays.indexOf(JSON.stringify(item))][incrementField]+=incrementValue;
    } else {
      // Pushing the original item to original items list
      unique_arrays_without_except.push(original_item);
      // Pushing the filtered items to list
      unique_arrays.push(JSON.stringify(item));
    }
  });
  
  return unique_arrays_without_except;
}

console.log(plusArrays(items,incrementField,exceptFields))

这是完成工作的功能。欢呼!