gpt4 book ai didi

javascript - 如何在javascript中分组并检测是否存在

转载 作者:行者123 更新时间:2023-11-30 08:20:20 24 4
gpt4 key购买 nike

我想每天检测此输入中是否存在特定代码:

const arrayA = [
{"date":"2018/9/10", "code":"A"},
{"date":"2018/9/10", "code":"B"},
{"date":"2018/9/10", "code":"C"},
{"date":"2018/9/10", "code":"A"},
{"date":"2018/9/11", "code":"A"},
{"date":"2018/9/11", "code":"C"}];

规则:如果当天有 B,则我们添加 X如果当天有 C,那么我们添加 Y如果 B & C 在我们添加 Y 的那一天出现

我在使用过滤器和 .some 的代码中迷失了自己...

预期输出

   const arrayOut = [
{"date":"2018/9/10", "code":"A"},
{"date":"2018/9/10", "code":"B"},
{"date":"2018/9/10", "code":"C"},
{"date":"2018/9/10", "code":"A"},
{"date":"2018/9/10", "code":"Y"},
{"date":"2018/9/11", "code":"A"},
{"date":"2018/9/11", "code":"B"},
{"date":"2018/9/11", "code":"X"}];

const arrayA = [
{"date":"2018/9/10", "code":"A"},
{"date":"2018/9/10", "code":"B"},
{"date":"2018/9/10", "code":"C"},
{"date":"2018/9/10", "code":"A"},
{"date":"2018/9/11", "code":"B"},
{"date":"2018/9/11", "code":"B"}];

var helper = [];
arrayA.map ( e => {
var key = e.date;
if(!helper[key]){
helper.push(key);
var arr = arrayA.filter(e => e.date == key && (e.code == "B" || e.code == "C"));

if(arr.length > 0) console.log("act is here");
else console.log("act not here");
}

});

最佳答案

我个人会将它映射到一个对象,这样您就可以进行简单的 bool 检查,而不仅仅是将该项目附加到列表中。

const arrayA = [
{"date":"2018/9/10", "code":"A"},
{"date":"2018/9/10", "code":"B"},
{"date":"2018/9/10", "code":"C"},
{"date":"2018/9/10", "code":"A"},
{"date":"2018/9/11", "code":"B"},
{"date":"2018/9/11", "code":"B"}];

const state = arrayA.reduce( (obj, state) => {
obj[state.date] = obj[state.date] || {}
obj[state.date][state.code] = true
return obj
}, {});

Object.entries(state).forEach(([date, codes]) => {
if (codes.C) {
arrayA.push({ date, code: 'Y' })
} else if (codes.B) {
arrayA.push({ date, code: 'X' })
}
})

console.log(arrayA)


在没有 Object.entries() 的情况下更新为相同的方法:

const arrayA = [
{"date":"2018/9/10", "code":"A"},
{"date":"2018/9/10", "code":"B"},
{"date":"2018/9/10", "code":"C"},
{"date":"2018/9/10", "code":"A"},
{"date":"2018/9/11", "code":"B"},
{"date":"2018/9/11", "code":"B"}];

const state = arrayA.reduce( (obj, state) => {
obj[state.date] = obj[state.date] || {}
obj[state.date][state.code] = true
return obj
}, {});

for (date in state)
{
if (state[date].C)
arrayA.push({ date, code: 'Y' });
else if (state[date].B)
arrayA.push({ date, code: 'X' });
}

console.log(arrayA);

关于javascript - 如何在javascript中分组并检测是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54635837/

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