循环将数组中的元素移动到末尾
Loop to shift elements in array to the end
假设我有一个数组
let arr = [
[0,1,0,4],
[1,0,1,2],
[0,0,1,1],
[0,1,0,1]
];
我想用高阶数组函数遍历数组,return一个数组,其中所有值都不等于n
(在我的例子中,假设n=0
) 将堆叠在数组的末尾:
console.log( arr.map( certainFunction ) );
//returns this;
[ [0,0,1,4],
[0,1,1,2],
[0,0,1,1],
[0,0,1,1] ]
是否可以使用高阶函数循环遍历 arr
和 return 上面的数组?
那么 certainFunction
会是什么样子呢?
let arr = [
[0,1,0,4],
[1,0,1,2],
[0,0,1,1],
[0,1,0,1]
];
arr = arr.map(ar => ar.sort((a, b) => a-b));
console.log(arr)
适用于您的情况,不确定您是否希望小于 n
的数字也适用
A higher-order 函数,按顺序排列 ;)
let separate = n => a => a.filter(x => x === n).concat(a.filter(x => x !== n));
//
let arr = [
[0,1,0,4],
[1,0,1,2],
[0,0,1,1],
[0,1,0,1]
];
newArr = arr.map(separate(1)) // move 1's to the start
console.log(newArr.map(x => x.join()))
或者,使用更多函数式编程:
let eq = a => b => a === b;
let not = f => a => !f(a);
let separate = n => a => a.filter(eq(n)).concat(a.filter(not(eq(n))));
这可以通过保留一个球门柱并将所有 arr[i] != n
推回该索引来线性完成。
function push_to_end (arr, n=0) {
// Begin by pushing items to the very end.
let index = arr.length - 1
for (let i = index; i > -1; i--) {
// If you encounter an integer not equal to end, place it
// at `index` and move the goalpost back one spot.
if (arr[i] !== n)
arr[index--] = arr[i]
}
// Fill everything up to the goalpost with `n`, as that is how
// many times we observed n.
for (let i = 0; i <= index; i++) {
arr[i] = n
}
return arr
}
在您的情况下,您可以将此函数应用于数组数组中的每个数组:
arr.map(a => push_to_end(a, n))
假设我有一个数组
let arr = [
[0,1,0,4],
[1,0,1,2],
[0,0,1,1],
[0,1,0,1]
];
我想用高阶数组函数遍历数组,return一个数组,其中所有值都不等于n
(在我的例子中,假设n=0
) 将堆叠在数组的末尾:
console.log( arr.map( certainFunction ) );
//returns this;
[ [0,0,1,4],
[0,1,1,2],
[0,0,1,1],
[0,0,1,1] ]
是否可以使用高阶函数循环遍历 arr
和 return 上面的数组?
那么 certainFunction
会是什么样子呢?
let arr = [
[0,1,0,4],
[1,0,1,2],
[0,0,1,1],
[0,1,0,1]
];
arr = arr.map(ar => ar.sort((a, b) => a-b));
console.log(arr)
适用于您的情况,不确定您是否希望小于 n
的数字也适用
A higher-order 函数,按顺序排列 ;)
let separate = n => a => a.filter(x => x === n).concat(a.filter(x => x !== n));
//
let arr = [
[0,1,0,4],
[1,0,1,2],
[0,0,1,1],
[0,1,0,1]
];
newArr = arr.map(separate(1)) // move 1's to the start
console.log(newArr.map(x => x.join()))
或者,使用更多函数式编程:
let eq = a => b => a === b;
let not = f => a => !f(a);
let separate = n => a => a.filter(eq(n)).concat(a.filter(not(eq(n))));
这可以通过保留一个球门柱并将所有 arr[i] != n
推回该索引来线性完成。
function push_to_end (arr, n=0) {
// Begin by pushing items to the very end.
let index = arr.length - 1
for (let i = index; i > -1; i--) {
// If you encounter an integer not equal to end, place it
// at `index` and move the goalpost back one spot.
if (arr[i] !== n)
arr[index--] = arr[i]
}
// Fill everything up to the goalpost with `n`, as that is how
// many times we observed n.
for (let i = 0; i <= index; i++) {
arr[i] = n
}
return arr
}
在您的情况下,您可以将此函数应用于数组数组中的每个数组:
arr.map(a => push_to_end(a, n))