javascript - 如何检查数组中是否有相等的值
问题描述
我有一系列产品,我会循环并将它们显示在一个项目上。但是,同一产品可能会在同一天被多次选择,因此我希望正确显示数量,但我不知道该怎么做。
所以我的数组看起来像这样:
[
{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);
}
其中“项目”是数组。
如上所述,我希望 ID 为“675”的产品被选择两次“2018-10-02”只显示一次,数量 = 2
我怎样才能做到这一点?
解决方案
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))
这是一个功能来完成你的工作。干杯!
推荐阅读
- python - 调用 groupby 函数后如何“自动填充”您的数据框?
- javascript - 如何防止 Node.js 12 工作线程立即终止?
- python - 如何从 Tkinter 条目中获取 3 位数字并将其转换为 IP 地址?
- java - spring boot项目定义依赖类为spring bean
- c# - 使用来自 C# 的解析参数执行 Python 脚本
- javascript - 窗口滚动事件——是否需要防止冒泡?
- awk - 从文件打印字符串和输入
- powershell - Windows 7 上的 PowerShell SMTPClient 失败(“需要身份验证”);适用于 Windows 10
- swift - 小窗口的大小
- python - 在 google colab 中运行 python 脚本,nohup 给出 ImportError