如何保留JavaScript数组中相同index属性的最后一个对象
保留数组中指定index的最后一个对象
原始数组
const obj = [ {fullCart: 5, halfCart: 4, smu: 3, stowage: 5, index: "FC-093"}, {fullCart: 5, halfCart: 4, smu: 8, stowage: 5, index: "FC-093"}, {fullCart: 5, halfCart: 4, smu: 0, stowage: 5, index: "FC-093"}, {fullCart: 5, halfCart: 5, smu: 3, stowage: 5, index: "FC-093"}, {fullCart: 5, halfCart: 7, smu: 3, stowage: 5, index: "FC-093"} ];
需求
移除所有index属性值为"FC-093"的前置对象,仅保留数组中最后一个符合该条件的对象,预期结果:
[{fullCart: 5, halfCart: 7, smu: 3, stowage: 5, index: "FC-093"}]
解决方案
方法1:记录最后一个匹配的索引
遍历数组时,每次遇到符合条件的对象就更新索引,最后根据索引取出目标对象:
// 找到最后一个index为FC-093的元素索引 const lastTargetIndex = obj.reduce((lastIdx, current, idx) => { return current.index === "FC-093" ? idx : lastIdx; }, -1); // 生成结果数组,无匹配项则返回空数组 const result = lastTargetIndex !== -1 ? [obj[lastTargetIndex]] : [];
方法2:用对象覆盖保留最后一个匹配项
利用对象键的唯一性,遍历数组时用符合条件的对象覆盖同一index对应的旧值,最后提取对象的值得到结果:
const result = Object.values( obj.reduce((acc, item) => { if (item.index === "FC-093") { acc[item.index] = item; } return acc; }, {}) );
这个方法还能扩展到数组存在多个不同index的场景,会自动保留每个index对应的最后一个对象。
方法3:从后往前查找第一个匹配项
将数组反转后找到第一个匹配元素,对应原数组的最后一个匹配项:
const reversedArr = [...obj].reverse(); const lastMatch = reversedArr.find(item => item.index === "FC-093"); const result = lastMatch ? [lastMatch] : [];
内容的提问来源于stack exchange,提问作者rishzeta
相关产品推荐
相关产品推荐

