Fe-interview: [js] 第555天 使用js写一个方法,使得数组的某个元素置顶

Created on 21 Oct 2020  ·  4Comments  ·  Source: haizlin/fe-interview

第555天 使用js写一个方法,使得数组的某个元素置顶

3+1官网

我也要出题

js

Most helpful comment

const bringToTop = (arr, index) => [arr[index], ...arr.filter((_, i) => i !== index)];

bringToTop(['A', 'B', 'C', 'D'], 2);  // ['C', 'A', 'B', 'D']

All 4 comments

const bringToTop = (arr, index) => [arr[index], ...arr.filter((_, i) => i !== index)];

bringToTop(['A', 'B', 'C', 'D'], 2);  // ['C', 'A', 'B', 'D']
let a = ['a', 'b', 'c', 'd'];
const pin2Top = (index, list) => [...list.splice(index, 1), ...list];
pin2Top(2, a);
// ["c", "a", "b", "d"]
let a = ['a', 'b', 'c', 'd'];
const pin2Top = (index, list) => [...list.splice(index, 1), ...list];
pin2Top(2, a);
// ["c", "a", "b", "d"]

我也考虑过用splice,但是该操作会mutate原数组,感觉还是返回新数组比较妥

let a = ['a', 'b', 'c', 'd'];
const pin2Top = (index, list) => [...list.splice(index, 1), ...list];
pin2Top(2, a);
// ["c", "a", "b", "d"]

我也考虑过用splice,但是该操作会mutate原数组,感觉还是返回新数组比较妥

对,没考虑到副作用。

Was this page helpful?
0 / 5 - 0 ratings

Related issues

haizhilin2013 picture haizhilin2013  ·  3Comments

haizhilin2013 picture haizhilin2013  ·  3Comments

haizhilin2013 picture haizhilin2013  ·  3Comments

haizhilin2013 picture haizhilin2013  ·  3Comments

haizhilin2013 picture haizhilin2013  ·  3Comments