I have the following array:
var arr = ["Toyota", "Hyundai", "Honda", "Mazda"];
I want to slice each element backwards, like:
var arr = ["Toyota", "Hyundai", "Honda", "Mazda"].slice(-2);
so it will return:
arr = ["Toyo", "Hyund", "Hon", "Maz"];
Is it possible? or is there anyway of doing this?
Not with
Array.protoype.slice()
, no. TryArray.prototype.map()
:See also:
String.prototype.slice()
You can't use
slice
directly, as it has a different meaning with an array and will return you a list of array elements.In order to do the slice on each element, you can use
.map()
(on IE9+):Alternatively, you could just use a loop:
or, in more modern syntax: