Slice each string-valued element of an array in Javascript -
i have following array:
var arr = ["toyota", "hyundai", "honda", "mazda"]; i want slice each element backwards, like:
var arr = ["toyota", "hyundai", "honda", "mazda"].slice(-2); so return:
arr = ["toyo", "hyund", "hon", "maz"]; is possible? or there anyway of doing this?
you can't use slice directly, has different meaning array , return list of array elements.
var arr = ["toyota", "hyundai", "honda", "mazda"]; arr.slice(0, -2) // returns elements ["toyota", "hyundai"] in order slice on each element, can use .map() (on ie9+):
var out = arr.map(function(v) { return v.slice(0, -2) })  // or using underscore.js wider compatibility var out = _.map(arr, function(v) { return v.slice(0, -2) }) alternatively, use loop:
var i, out = []; (i = 0; < arr.length; ++i) {     out.push(arr[i].slice(0, -2)); } 
Comments
Post a Comment