[英]count occurrences of items in an array from an nested items in an array of objects javascript
I have this array of dates.我有这个日期数组。
const dateArray = ["7/12/2021","7/13/2021","7/14/2021","7/15/2021"]
and I am trying to see if any of these dates appear inside my other array of array of objects, those dates will match something inside the objects.我想看看这些日期中是否有任何一个出现在我的另一个对象数组中,这些日期将匹配对象中的某些内容。
const data = [
[ { id: 1, date: "7/13/2021" }, { id:2, date: "7/15/2021" } ],
[ { id: 1, date: "7/14/2021" }, { id:2, date: "7/15/2021" } ],
]
so if date doesn't match I want to return 0 for that date.所以如果日期不匹配,我想为那个日期返回 0。 something like this
像这样的东西
const result = [
[0, 1, 0, 1],
[0, 0, 1, 1]
]
I tried something like this.....我试过这样的事情......
var getResult = (dateArray, data) => {
const result = []
let index = 0;
for (let i = 0; i < dateArray.length; i++) {
for (let j = 0; j < data.length; j++) {
let count = 0
if (dateArray[i] === data[j][index].date) {
count++
index++
if (index === data[i].length) {
return
}
}
result.push(count)
}
}
console.log(result)
}
but it doesn't work of course.... Thank you for your help!但它当然不起作用....感谢您的帮助!
const dateArray = ["7/12/2021","7/13/2021","7/14/2021","7/15/2021"], data = [ [ { id: 1, date: "7/13/2021" }, { id:2, date: "7/15/2021" } ], [ { id: 1, date: "7/14/2021" }, { id:2, date: "7/15/2021" } ], ]; // iterate over data const result = data.map(arr => { // get occurences count of current array dates const occurences = arr.reduce((map, {date}) => map.set(date, (map.get(data) || 0) + 1) , new Map); // return list of occurences for dateArray elements return dateArray.map(date => occurences.get(date) || 0); }, []); console.log(result);
You can do something like this你可以做这样的事情
const dateArray = ["7/12/2021", "7/13/2021", "7/14/2021", "7/15/2021"]; const data = [ [{ id: 1, date: "7/13/2021" }, { id: 2, date: "7/15/2021" }], [{ id: 1, date: "7/14/2021" }, { id: 2, date: "7/15/2021" }], ]; const result = data.map(item => { const resArr = (new Array(dateArray.length)).fill(0); item.forEach(entity => { const index = dateArray.findIndex(dateItem => dateItem == entity.date); if (index >= 0) { resArr[index]++; } }); return resArr; }); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.