gpt4 book ai didi

javascript - 循环将数组中的元素移到末尾

转载 作者:行者123 更新时间:2023-11-28 14:38:26 25 4
gpt4 key购买 nike

假设我有一个数组

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 会是什么样子?

最佳答案

一个高阶函数,按顺序;)

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

关于javascript - 循环将数组中的元素移到末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49079971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com