Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slice each string-valued element of an array in Javascript

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?

like image 236
Gobrisebane Avatar asked Oct 24 '25 16:10

Gobrisebane


1 Answers

You 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 compatibility
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)
}
like image 165
Tom Fenech Avatar answered Oct 26 '25 05:10

Tom Fenech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!