gpt4 book ai didi

Javascript - 如何计算数组 reduce() 方法中对象数组的唯一 ID(值)

转载 作者:行者123 更新时间:2023-12-05 01:49:39 24 4
gpt4 key购买 nike

您好,我一直在练习 reduce 方法的挑战以真正理解它,但这个主题让我感到困惑。

const orders = [
{ livingId: 996, cash: 30500.35, tax: 0.06, isDisputed: true},
{ livingId: 910, cash: 100, tax: 0.08, isDisputed: true },
{ livingId: 912, cash: 4200.11, tax: 0.06 },
{ livingId: 996, cash: 99.12, tax: 0.06, isDisputed: false },
{ livingId: 910, cash: 0.00, tax: 0.08, isShipped: true },
{ livingId: 996, cash: 10, tax: 0.06, isDisputed: true },
];

const result = orders.reduce(
(arr, current) => {
const numOrders = arr.numOrders + 1;
const uniqueId = [...new Set([current.livingId])] //returns [996]
console.log("arr.uniqueId= "+ arr.uniqueId)
console.log("current.livingId= "+ current.livingId)
console.log("current.livingId + arr.uniqueId= "+ uniqueId)
return {
numOrders,
uniqueId,
};
},
{
numOrders: 0,
uniqueId: 0,
},
);

console.log(result)

如何从 livingId 返回唯一 ID 值的总数?连同我当前获取总订单的方法。

预期结果:订单数:6livingId: 3

我已经尝试在控制台记录多种方法,如 filter、includes 并发现最干净的是新的 Set 方法,但它只返回来自返回 [996] 的 livingId 的最后一个可迭代数组。返回的 .length 肯定是 1 而不是 3。我也试过这个,但它返回所有值。

const uniqueId = [...new Set([arr.uniqueId, current.livingId])] // 0,996,910,912,996,910,996

最佳答案

如果你想用reduce来做到这一点:

const orders=[{livingId:996,cash:30500.35,tax:.06,isDisputed:!0},{livingId:910,cash:100,tax:.08,isDisputed:!0},{livingId:912,cash:4200.11,tax:.06},{livingId:996,cash:99.12,tax:.06,isDisputed:!1},{livingId:910,cash:0,tax:.08,isShipped:!0},{livingId:996,cash:10,tax:.06,isDisputed:!0}];

const ids = orders.reduce((set, c) => {
set.add(c.livingId);
return set;
}, new Set());

console.log(ids.size);

或者:map在数组上获取一个 id 数组,将该数组添加到一个集合中,并获取它的 size .

const orders = [
{ livingId: 996, cash: 30500.35, tax: 0.06, isDisputed: true},
{ livingId: 910, cash: 100, tax: 0.08, isDisputed: true },
{ livingId: 912, cash: 4200.11, tax: 0.06 },
{ livingId: 996, cash: 99.12, tax: 0.06, isDisputed: false },
{ livingId: 910, cash: 0.00, tax: 0.08, isShipped: true },
{ livingId: 996, cash: 10, tax: 0.06, isDisputed: true }
];

const idsLen = new Set(orders.map(order => order.livingId)).size;

console.log(idsLen);

关于Javascript - 如何计算数组 reduce() 方法中对象数组的唯一 ID(值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73843270/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com