admin管理员组文章数量:1278947
I have an array like this:
array = [1,2,3,4,5,6,7,8]
and i want to remove for example the 4 last values so as my array bees this: array = [1,2,3,4] I used array.splice(array.length - 4, 1) but it didn't work. Any ideas?
I have an array like this:
array = [1,2,3,4,5,6,7,8]
and i want to remove for example the 4 last values so as my array bees this: array = [1,2,3,4] I used array.splice(array.length - 4, 1) but it didn't work. Any ideas?
Share Improve this question asked Mar 7, 2018 at 18:59 RamAlxRamAlx 7,34424 gold badges64 silver badges110 bronze badges 1- possible duplicate stackoverflow./questions/7538519/… – Doug Clark Commented Mar 7, 2018 at 19:04
5 Answers
Reset to default 8You can use the function slice
as follow:
.slice(0, -4)
This approach doesn't modify the original Array
// +---- From 0 to the index = (length - 1) - 4,
// | in this case index 3.
// vvvvv
var array = [1,2,3,4,5,6,7,8].slice(0, -4);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
This approach modifies the original Array
var originalArr = [1, 2, 3, 4, 5, 6, 7, 8];
// +---- Is optional, for your case will remove
// | the elements ahead from index 4.
// v
originalArr.splice(-4, 4);
console.log(originalArr);
//----------------------------------------------------------------------
originalArr = [1, 2, 3, 4, 5, 6, 7, 8];
// +---- Omitting the second param.
// |
// v
originalArr.splice(-4);
console.log(originalArr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Docs
Array.prototype.splice()
Array.prototype.slice()
Removing 4 elements from the end a list
var myList = [1,2,3,4,5,6,7,8];
var removed = myList.splice(-myList.length-4, 4);
https://jsfiddle/etuf28bj/4/
You can use a length property
let a = [1,2,3,4,5,6,7,8];
a.length -= 4 // delete 4 items from the end
array.splice(0,4)
will remove 0 elements from the array begin and 4 elements from array ends
You can also use filter
for removing element(it will not modify existing array)
array = [1,2,3,4,5,6,7,8];
array1=array.filter((x,i)=>i<array.length-4);
console.log(array1);
Or you can use splice
(it will change array itself)
array = [1,2,3,4,5,6,7,8];
array.splice(-4);
console.log(array);
本文标签: javascriptRemove nth elements from the end of an arrayStack Overflow
版权声明:本文标题:javascript - Remove n-th elements from the end of an array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741225853a2361843.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论