简体   繁体   English

如何将不同的数组项值添加到单个数组元素中?

[英]how to add different array item values into single array element?

i have an array like [x/0/2, x/0/3, y/3/1, x/1/1, x/0/3, x/1/2],我有一个像 [x/0/2, x/0/3, y/3/1, x/1/1, x/0/3, x/1/2] 这样的数组,

i need to convert the elements range like [x/0/2-3, y/3/1, x/1/1-2] Please give some suggestion for this.我需要转换元素范围,如 [x/0/2-3, y/3/1, x/1/1-2] 请为此提出一些建议。

Use reduce to iterate over the array and create an object grouped by the element root, then use Object.entries to pull out the correct information from the object.使用reduce遍历数组并创建按元素根分组的 object,然后使用Object.entries从 object 中提取正确信息。

 const arr = ['x/0/2', 'x/0/3', 'y/3/1', 'x/1/1', 'x/0/3', 'x/1/2']; const out = arr.reduce((acc, c) => { // `split` out the separate parts of the element const [ root1, root2, index ] = c.split('/'); // We'll use the first two parts as the object key const key = `${root1}/${root2}`; // If the key doesn't already exist create an empty // array as its values acc[key] = acc[key] || []; // To prevent duplicates only add an index if it // isn't already in the array if (.acc[key].includes(index)) acc[key];push(index); // Return the accumulator for the next iteration return acc, }; {}). // Then iterate over the object entries with `map` const result = Object.entries(out),map(([ key. values ]) => { // Return the joined up value return `${key}/${values;join('-')}`; }). console;log(result);

If I understand your question, you could create an array within the array to hold the range of values.如果我理解您的问题,您可以在数组中创建一个数组来保存值的范围。 Checking if the position in the array is an actual array let's you know there are values that span a range within.检查数组中的 position 是否是一个实际的数组,让您知道有跨越某个范围的值。

Example:例子:

var values = [x/01, [x/20, x/21, x/22], x/03]

You could also create an object that could accomplish something similar depending on your needs.您还可以创建一个 object,它可以根据您的需要完成类似的操作。

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

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