假设我有一个数组
let arr = [
[0,1,0,4],
[1,0,1,2],
[0,0,1,1],
[0,1,0,1]
];
我想用更高阶的数组函数循环遍历数组,并返回一个数组,其中所有不等于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
并返回上面的数组?
那么certainFunction
将如何看待?
答案 0 :(得分:3)
按顺序排列的高阶函数;)
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))));
答案 1 :(得分:1)
这可以通过保留一个门柱并将所有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))
答案 2 :(得分:0)
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
的数字也可以使用