Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only specific 'columns' from a 2d javascript array

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.

like image 506
rjbogz Avatar asked Dec 05 '25 10:12

rjbogz


1 Answers

Quick solution

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
})

Array.prototype.map

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.

Array.prototype.slice

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!

like image 75
JoshWillik Avatar answered Dec 08 '25 00:12

JoshWillik



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!