首页 > 解决方案 > 如何将json按连续值分组到一个数组中

问题描述

所以我试图将这些值分组到节和行匹配的位置,并具有 startSeat 和 endSeat 的连续顺序,我知道我可以使用 reduce 函数。我什么都试过了就是想不通

 const y = [{sec: "100", row: "12", startSeat: 1, endSeat: 2},
            {sec: "125", row: "10", startSeat: 1, endSeat: 2},
            {sec: "125", row: "10", startSeat: 3, endSeat: 4},
            {sec: "125", row: "10", startSeat: 9, endSeat: 10}];

因此,例如,有 3 个项目的“125”部分,但其中只有 2 个具有连续座位,1、2、3、4 具有 9,10 的项目具有相同的部分但不连续,我只想要那些连续的组合成一个数组。我的新数组应该是这样的

          [{sec: "125", row: "10", startSeat: 1, endSeat: 2},
           {sec: "125", row: "10", startSeat: 3, endSeat: 4}]

其他一切都应该被忽略

   var result =y.reduce( (previousValue, currentValue, currentIndex, a) => {
    
   if (!currentIndex || (currentValue.startSeat - a[currentIndex - 1].endSeat === 
    1))previousValue.push([]);

   previousValue[previousValue.length - 1].push(currentValue);

   return previousValue;
   }, []);

   console.log(result);

标签: javascriptjquery

解决方案


你可以尝试这样的事情:

const y = [{sec: "100", row: "12", startSeat: 1, endSeat: 2},
            {sec: "125", row: "10", startSeat: 1, endSeat: 2},
            {sec: "125", row: "10", startSeat: 3, endSeat: 4},
            {sec: "125", row: "10", startSeat: 5, endSeat: 6},
            {sec: "125", row: "10", startSeat: 9, endSeat: 10}];

let x = [];
y.forEach(function(element, index, arr) {
    let currentEl;
    for (var i=index+1; i < arr.length; i++) {
    currentEl = arr[i];
    if (element.sec == currentEl.sec && element.row == currentEl.row && Math.abs(currentEl.startSeat - element.endSeat) == 1) {
      if (!x.includes(element))
        x.push(element);
      if (!x.includes(currentEl))
        x.push(currentEl);
    }
  }
})

console.log(x);

此代码迭代y数组,并为每个当前元素(currentEl变量)将它与接下来的每个其他元素进行比较,并检查它是否符合“连续座位”标准。例如,在第一次forEach迭代中,当前元素的索引为 0,因此它与索引为 1、2、3 和 4 的元素进行比较。如果满足条件,则将元素推入新数组,仅当他们不在那里。下一个当前元素(索引为 1)与索引为 2、3 和 4 的元素进行比较。依此类推,直到处理整个数组。


推荐阅读