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?
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?
Share Improve this question edited Sep 20, 2014 at 17:49 Brock Adams 93.7k23 gold badges241 silver badges305 bronze badges asked Sep 20, 2014 at 15:48 GobrisebaneGobrisebane 1331 gold badge4 silver badges7 bronze badges 1- And you don't want to iterate through each array member via a for loop and slice each array member by 2 characters? – The One and Only ChemistryBlob Commented Sep 20, 2014 at 16:03
2 Answers
Reset to default 6You can't use slice
directly, as it has a different meaning with an array and will return you a list of array elements.
var arr = ["Toyota", "Hyundai", "Honda", "Mazda"]
arr.slice(0, -2) // returns the elements ["Toyota", "Hyundai"]
In order to do the slice on each element, you can use .map()
(on IE9+):
var out = arr.map(function(v) { return v.slice(0, -2) })
// or using underscore.js for wider patibility
var out = _.map(arr, function(v) { return v.slice(0, -2) })
// or using a more modern arrow function
var out = arr.map(v => v.slice(0, -2))
Alternatively, you could just use a loop:
var i, out = []
for (i = 0; i < arr.length; ++i) {
out.push(arr[i].slice(0, -2))
}
or, in more modern syntax:
const out = new Array(arr.length)
for (let i = 0; i < arr.length; ++i) {
out[i] = arr[i].slice(0, -2)
}
Not with Array.protoype.slice()
, no. Try Array.prototype.map()
:
var arr = ["Toyota","Hyundai","Honda","Mazda"].map(s => s.slice(0, -2));
console.log(arr);
See also: String.prototype.slice()