从javascript对象数组中的嵌套项计算数组中项的出现次数

gkl3eglg  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(321)

我有一系列的日期。

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" } ],
]

所以,如果日期不匹配,我希望返回0作为该日期。像这样的

const result = [
     [0, 1, 0, 1],
     [0, 0, 1, 1]
]

我试过这样的。。。。。

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)
}

但它当然不起作用。。。。谢谢你的帮助!

xesrikrc

xesrikrc1#

你可以这样做

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);
csbfibhn

csbfibhn2#

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);

相关问题