目前我有一个一维数组,例如['thing1', 'cond1', 'thing2', 'cond2', 'thing3']
我想将每个项配对,以创建一个新的多维数组,如[['thing1', 'cond1'], ['thing2', 'cond2'], ['thing3']]
。我不介意最后一项是['thing3', undefined]
——如果有什么不同的话,这是最好的,除非有人认为这是一种糟糕的做法。
到目前为止,我有
const pair = (arr) => {
let paired = [];
for (i = 0; i < arr.length; i += 2) {
paired.push([arr[i], arr[i+1]]);
}
return paired;
}
你可以在我的JS Bin示例中尝试一下。
AFAIA工作得非常好,但我希望使用现代JS尽可能简洁,而且我的数组操作没有达到应有的水平。
提前感谢所有尝试过的人。
让挑战。。。开始!
您可以使用带有索引变量的while
循环。推一对,取slice
。
const pair = array => {
let paired = [],
i = 0;
while (i < array.length) paired.push(array.slice(i, i += 2));
return paired;
}
var array = ['thing1', 'cond1', 'thing2', 'cond2', 'thing3'],
paired = pair(array);
console.log(paired);
您可以试试这个regex
。通过使用正则表达式查找数字来对值进行分组。
const data = ['thing1', 'cond1', 'thing2', 'cond2', 'thing3'];
const result = {};
data.forEach(value => {
const index = value.replace(/[^d.]/g, '');
if (typeof result[index] == 'undefined') {
result[index] = [];
}
result[index].push(value);
});
const array = Object.values(result);
console.log(array);