有没有一种方法可以在一行内切割数组的元素并返回切割后的数组?

huangapple go评论67阅读模式
英文:

Is there a way to splice out elements of an array and return the spliced array in one line?

问题

Sure, here's the translated code part:

如果我有一个数组 `a = [1,2,3,4]` 并且我想要返回去掉 `3` 的数组有两种方法可以做到

    let b = [...a] // 或者 a.slice()
    b.splice(2,1)
    return b

或者

    return [...a.slice(0,2), ...a.slice(3,4)]

第二种方法的优点是它只有一行缺点是它有点啰嗦我考虑过编写一个包含第一种方法逻辑的辅助函数这样我就可以在其他地方一行内调用它

是否有其他替代方法类似于 `splice`但返回被切割的数组而不是改变它并返回被切割的元素
英文:

If I have an array a = [1,2,3,4] and I want to return it with the 3 removed, there are two ways I can do it:

let b = [...a] // or a.slice()
b.splice(2,1)
return b

or

return [...a.slice(0,2), ...a.slice(3,4)]

Advantage of the second is that it's one line. Disadvantage is that it's verbose. I thought of writing a helper function that contains the logic of the first approach, so that I'd be able to call it in one line elsewhere.

Is there an alternative? Something like splice but that returns that spliced array rather than mutating it and returning the spliced-out elements.

答案1

得分: 2

Since you know the indicies you want to remove, you can use the Array.prototype.filter method.

const a = [1,2,3,4];
const b = a.filter((_, i) => i !== 2);
console.log(b);

If you need to remove a range, you can just do something like 2 < i || i > 3.

filter makes a copy of the array, copying the values where the callback function evaluates truthy and ignores the values where the callback function evaluates falsy.

英文:

Since you know the indicies you want to remove, you can use the Array.prototype.filter method.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const a = [1,2,3,4];
const b = a.filter((_, i) =&gt; i !== 2);
console.log(b);

<!-- end snippet -->

If you need to remove a range, you can just do something like 2 &lt; i || i &gt; 3.

.filter makes a copy of the array, copying the values where the callback function evaluates truthy and ignores the values where the callback function evaluates falsy.

huangapple
  • 本文由 发表于 2023年2月7日 04:45:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75366404.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定