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



我有一个数组,如[x/0/2,x/0/3,y/3/1,x/1/1,x/0/3,x/1/2],

我需要转换元素范围,如[x/0/2-3,y/3/1,x/1/1-2]请对此提出一些建议。

使用reduce迭代数组并创建按元素根分组的对象,然后使用Object.entries从对象中提取正确的信息。

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);

如果我理解你的问题,你可以在数组中创建一个数组来容纳值的范围。检查数组中的位置是否为实际数组,可以让您知道其中存在跨越范围的值。

示例:

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

你也可以创建一个对象,根据你的需要可以完成类似的事情。

最新更新