I have an array in js:
myArray = [['1','2','3'],['4','5','6'],['7','8','9']];
How can I produce an array like this:
myAlteredArray = [['2','3'],['5','6'],['8','9']];
I basically want to exclude the first column out of the array.
The easiest way to do this would be to use map and slice.
var subsections = myArray.map(function (subarray) {
return subarray.slice(1)
})
You could also manipulate the subsections in any way you want by doing the following:
var subsections = myArray.map(function (subarray) {
var subsection = subarray.slice(1)
subsection[1] = parseInt(subsection[1], 10) // parse index 1 in base 10
return subsection
})
myArray.map(callback) executes callback on each element in myArray and returns a new array made up of all the return values. For example:
[1, 2, 3].map(function (number) { return 10 - number })
would return [9, 8, 7] and leave the original array unchanged.
myArray.slice(start, [end]) will return a subsection of myArray in a new array. If you only pass start, end is assumed to be the end of the array. For example:
['dogs', 'cats', 'fish', 'lizards'].slice(2) == ['fish', 'lizards']
['dogs', 'cats', 'fish', 'lizards'].slice(1, 3) == ['cats', 'fish']
Fun fact: .slice() works on strings too!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With