简体   繁体   English

当在 Javascript 中重复时,如何循环创建具有两个元素的另一个数组?

[英]How to loop to create another array with two elements when they are repeated in Javascript?

I want to create a two-dimensional array from another existent array, which is scraped from a website through document.querySelectorAll().我想从另一个现有数组创建一个二维数组,该数组是通过 document.querySelectorAll() 从网站上抓取的。 I want to add from two to two depending on the elements of the array.我想根据数组的元素从两个添加到两个。 Let me show you an example to make me more understandable.让我给你举个例子,让我更容易理解。

myArray = ["price $33", "extra $2", "price $54", "price $20", "extra $3.5", "price $25", "extra $2", "price $31"]

In theory, every two elements are paired (the strings with "extra" are related with the strings with "price").理论上,每两个元素都是配对的(带有“extra”的字符串与带有“price”的字符串相关)。 However, as you can see there are prices that do not have extras .但是,如您所见,有些价格没有额外费用 Every extra comes with the previous price.每个额外的价格都带有以前的价格。 I want to add the price and its extra together as well as the price alone.我想将价格及其额外费用以及单独的价格加在一起。 Like this:像这样:

new array = [["price $33", "extra $2"], ["price $54"], ["price $20", "extra $3.5"], ["price $25", "extra $2"], ["price $31"]]

Thank you very much!非常感谢!

You could reduce the array and check if the string starts with extra , then push the the last array of add a new array with the string.您可以减少数组并检查字符串是否以extra开头,然后将最后一个数组推入添加新数组的字符串。

 var array = ["price $33", "extra $2", "price $54", "price $20", "extra $3.5", "price $25", "extra $2", "price $31"], result = array.reduce((r, s) => { if (s.startsWith('extra')) r[r.length - 1].push(s); else r.push([s]); return r; }, []); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

You could do this with clever use of reduce including a flag to say whether to skip the next element.你可以巧妙地使用reduce来做到这一点,包括一个标志来说明是否跳过下一个元素。 Something like below:如下所示:

 var myArray = ["price $33", "extra $2", "price $54", "price $20", "extra $3.5", "price $25", "extra $2", "price $31"]; var newArray = myArray.reduce( (agg, item, index, arr) => { if(agg.skipNext) { agg.skipNext = false; return agg; } if(index < arr.length-1 && arr[index+1].startsWith("extra")) { agg.skipNext = true; agg.push([item,arr[index+1]]); } else agg.push([item]); return agg; },[]); console.log(newArray);

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

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