[英]Replace existing file and push to top index of array using Javascript
如果它是真的,我需要将我在 if 语句中找到的当前文件推送到顶部项目......所以我找到它并将其传输到顶部......
allProducts.forEach(
(product) =>
checkIfProductIsMoreThen200(product.price) &&
allProducts.unshift(product)
);
这是我的尝试,但没有工作......
他把我推到顶部索引,但给我留下了旧项目......然后它复制了我当前的项目......我不想复制这些项目..
看看Array.splice() ,它应该可以为您解决问题。
const allProducts = [1, 2, 3]; console.log(`Before: ${allProducts}`) allProducts.forEach((product, index) => product == 3 && allProducts.unshift(allProducts.splice(index, 1)[0])); console.log(`After: ${allProducts}`)
您的代码在循环时确实会使数组更长,这是一个坏主意。
相反,您可以使用sort
(用于短代码):
allProducts.sort((a, b) => checkIfProductIsMoreThen200(b.price) -
checkIfProductIsMoreThen200(a.price));
对于(非常)长的数组,这样做会更有效:
allProducts = allProducts.filter(a => checkIfProductIsMoreThen200(a.price)).concat(
allProducts.filter(a => !checkIfProductIsMoreThen200(a.price))
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.