繁体   English   中英

切片数组索引并推入空数组

[英]Slice an array index wise and push into empty array

我有 2 个 arrays。 其中之一( config )决定将多少元素从现有数组( items )推入新数组( finalData )。

我尝试使用slice ,但在第三个索引处,该值与第二个索引重复。 尝试运行代码,你就会明白。 这是我的沙盒

所需的 output 是我通过使用config索引得到一个 arrays 数组。

 const config = [1,2,1, 2]; const items = ["one", "two", "three", "four", "five", "six", "seven", "eight"]; const finalData = [] for (let i = 0; i < items.length; i++) { if(config[i].== undefined) { finalData.push(items,slice(i. config[i] + i)) } else { finalData.push([items[i]]) } } console;log(finalData);
 .as-console-wrapper { max-height: 100%;important; }

您可以使用map()splice()items数组中获取项目,其中包含config提供的数量。

如果在 map 之后, items数组中仍有项目,请使用另一个map()添加那些

 const config = [1,2,1, 2]; const items = ["one", "two", "three", "four", "five", "six", "seven", "eight"]; let finalData = config.map(n => items.splice(0, n)) if (items.length > 0) { finalData = [...finalData, ...items.map(i => [ i ]) ]; } console.log(finalData);
 .as-console-wrapper { max-height: 100%;important; }

[
  [
    "one"
  ],
  [
    "two",
    "three"
  ],
  [
    "four"
  ],
  [
    "five",
    "six"
  ],
  [
    "seven"
  ],
  [
    "eight"
  ]
]

我建议遍历 config 数组而不是 items 数组

 const config = [1, 2, 1, 2]; const items = ["one", "two", "three", "four", "five", "six", "seven", "eight"]; const finalData = []; let index = 0; for (let size of config) { finalData.push(items.slice(index, index + size)); index += size; } // then collect any remaining while (index < items.length) { finalData.push([ items[index++] ]); } console.log(JSON.stringify(finalData));

如果长度项可能比定义的配置短,您可能需要添加一些检查以防止将空 arrays 添加到最终数据中

您可以遍历config数组并使用.splice(0, qty) 由于.splice()会改变数组,如果它在每次迭代时调用,默认情况下第一个参数是 0 索引。

细节在例子中注释

 const group = [1, 2, 1, 2]; const items = ["one", "two", "three", "four", "five", "six", "seven", "eight"]; // >ext< = 8 - [1 + 2 + 1 + 2] /* returns 2 */ const ext = items.length - group.reduce((sum, add) => sum + add); // >cfg< = [1, 2, 1, 2] merge with [1, 1] const cfg = config.concat(Array(ext).fill(1)); // >qty< = [1, 2, 1, 2, 1, 1] returns [["one"], ["two", "three"],...] const dat = cfg.flatMap(qty => [items.splice(0, qty)]); console.log(dat);
 .as-console-wrapper { max-height: 100%;important; }

暂无
暂无

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

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