简体   繁体   English

使用 Javascript 替换现有文件并推送到数组的顶部索引

[英]Replace existing file and push to top index of array using Javascript

I need to push the current file that I find in the if statement if it is true, to the top item ... so I find it and transfer it to the top ....如果它是真的,我需要将我在 if 语句中找到的当前文件推送到顶部项目......所以我找到它并将其传输到顶部......

  allProducts.forEach(
    (product) =>
      checkIfProductIsMoreThen200(product.price) && 
      allProducts.unshift(product)
  );

this is my try but no work...这是我的尝试,但没有工作......

he pushes me into the top index but leave me the old items ... and then it duplicates my current ones ... I don't want to duplicate the items ..他把我推到顶部索引,但给我留下了旧项目......然后它复制了我当前的项目......我不想复制这些项目..

Have a look at Array.splice() , it should do the trick for you.看看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}`)

Your code will indeed make the array longer while looping, which is a bad idea.您的代码在循环时确实会使数组更长,这是一个坏主意。

Instead you could use sort (for short code):相反,您可以使用sort (用于短代码):

allProducts.sort((a, b) => checkIfProductIsMoreThen200(b.price) - 
                           checkIfProductIsMoreThen200(a.price));

For (very) long arrays, it will be more efficient to do this:对于(非常)长的数组,这样做会更有效:

allProducts = allProducts.filter(a => checkIfProductIsMoreThen200(a.price)).concat(
    allProducts.filter(a => !checkIfProductIsMoreThen200(a.price))
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM