【问题标题】:Array concating based on sequence of object Ids in between specific objects基于特定对象之间的对象 ID 序列的数组 concat
【发布时间】:2021-08-09 09:53:53
【问题描述】:

我有两个不同的数组,如果对象 id 之间有可用的对象,我想从第二个数组中添加数组对象。

firstArray = [
    { id: 'LOA13', type: 'LOAD', otherProperty: 11 },
    { id: 'UNA1', type: 'UNLOAD', otherProperty: 22 },
    { id: 'LOA14', type: 'LOAD', otherProperty: 33 },
    { id: 'UNA15', type: 'UNLOAD', otherProperty: 44 }
]

secondArray = [
    { id: 'LOA13', type: 'LOAD', otherProperty: 12 },
    { id: '123', type: 'DRAG', otherProperty: 34 }, 
    { id: 'UNA1', type: 'UNLOAD', otherProperty: 56 },
    { id: 'LOA14', type: 'LOAD', otherProperty: 12 },
    { id: '456', type: 'DRAG', otherProperty: 1212 },
    { id: '789', type: 'DRAG', otherProperty: 9898 },   
    { id: 'UNA15', type: 'UNLOAD', otherProperty: 56 }
]

如果在特定的 Ids 序列之间找到任何对象,那么它们应该添加到数组中的结果中。

预期的结果是这样的:

[
    { id: 'LOA13', type: 'LOAD', otherProperty: 11 }, 
    { id: '123', type: 'DRAG', otherProperty: 34 }, // ADDED as found between ID= LOA13 and UNA1
    { id: 'UNA1', type: 'UNLOAD', otherProperty: 22 }, 
    { id: 'LOA14', type: 'LOAD', otherProperty: 33 },
    { id: '456', type: 'DRAG', otherProperty: 1212 }, // ADDED as found between ID=LOA14 and UNA15
    { id: '789', type: 'DRAG', otherProperty: 9898 }, // ADDED as found between ID=LOA14 and UNA15  
    { id: 'UNA15', type: 'UNLOAD', otherProperty: 44 }
]

【问题讨论】:

  • Id 没有特定的顺序。我只需要第二个数组中的任何对象在第一个数组的特定 id 之间,那么它应该在结果数组中。

标签: javascript arrays typescript


【解决方案1】:

请使用此代码。

const resultArray = secondArray.map((val, index) => {
    if(firstArray.filter(value => value.id == val.id).length == 0) {
        let pos = index - 1;
        while(firstArray.filter(value => value.id == secondArray[pos].id).length == 0) pos--;
        const betweenIndex = firstArray.indexOf(firstArray.filter(value => value.id == secondArray[pos].id)[0]);
        const result = "ADDED as found between ID= " + firstArray[betweenIndex].id + " and " + firstArray[betweenIndex+1].id;
        return {...val, result};
    }
    return val;
});
console.log(resultArray);

【讨论】:

  • 结果有点不同,它从 secondArray 中返回对象,用于类似 ID - LOA13 和 UNA1。查看结果中的“otherProperty”值。它应该从 firstArray 返回。
猜你喜欢
  • 2020-09-08
  • 1970-01-01
  • 1970-01-01
  • 2019-03-11
  • 2016-07-18
  • 2020-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多