英文:
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) => i !== 2);
console.log(b);
<!-- end snippet -->
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论