gpt4 book ai didi

javascript - 从数组中删除最后添加的值而不改变它

转载 作者:太空宇宙 更新时间:2023-11-04 16:02:44 27 4
gpt4 key购买 nike

dontMutateMeArray=[1,2,3,3,3,4,5];
toBeRemoved=3;

newArray=dontMutateMeArray.something(toBeRemoved); // [1,2,3,3,4,5]
iDontWantArray=dontMutateMeArray.filter(value=>value===toBeRemoved); // [1,2,4,5]

我确实也需要它来存储对象数组。我特别需要删除最后添加的对象 (即数组中索引较高的对象)。像这样的东西:

dontMutateMeArray=[{id:1},{id:2},{id:3,sth:1},{id:3,sth:42},{id:3,sth:5},{id:4},{id:5}];
toBeRemoved=3;

newArray=dontMutateMeArray.something(toBeRemoved); // [{id:1},{id:2},{id:3,sth:1},{id:3,sth:42},{id:4},{id:5}]
iDontWantArray=dontMutateMeArray.filter(obj=>obj.id===toBeRemoved); // [{id:1},{id:2},{id:4},{id:5}]
iDontWantArray2=dontMutateMeArray.blahBlah(toBeRemoved); // [{id:1},{id:2},{id:3,sth:1},{id:3,sth:5},{id:4},{id:5}]

最佳答案

您可以从右侧迭代并检查闭包。

var dontMutateMeArray = [{ id: 1 }, { id: 2 }, { id: 3, sth: 1 }, { id: 3, sth: 42 }, { id: 3, sth: 5 }, { id: 4 }, { id: 5 }],
toBeRemoved = 3,
newArray = dontMutateMeArray.reduceRight((found => (r, a) => (!found && a.id === toBeRemoved ? found = true : r.unshift(a), r))(false), []);

console.log(newArray);

关于javascript - 从数组中删除最后添加的值而不改变它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42141784/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com