1

I have a JS array that's filled with data as follows:

var myarr = [[new Date("2011-12-01"), 389, 380.75, 382.54, 387.93],
[new Date("2011-11-30"), 382.28, 378.3, 381.29, 382.2]...]

Is there some way to only select the entire date column and the last number of each row? I'm looking for an output that's something like this:

[[new Date("2011-12-01"), 387.93],[new Date("2011-11-30"), 382.2]...]

2 Answers 2

1
var myCollapsedArr = [[myarr[0][0], myarr[0][myarr[0].length-1]], [myarr[1][0], myarr[1][myarr[1].length-1]];

Or in a for loop:

var myCollapsedArr = [];

for(var i = 0; i<myarr.length; i++) {
    myCollapsedArr.push([myarr[i], [myarr[i][myarr[i].length-1]]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Note that it's a good practice to cache the length of your array in the loop setup, otherwise you're re-calculating it every time. Not a big speed hit, but never a bad idea. for (var i=0,len=myarr.length;i<len;++i) …
Thanks, Elliot. The loop worked. Although I was thinking that there might be some function such as slice that does it without making use of loops. Cheers!
1

Option 1 - Simple for Loop

// Create array to hold new values
var newArray = [];
// Loop through existing array and pull out data
for(var i = 0; i < myarr.length; i++) {
    newArray.push([myarr[i][0], myarr[i][myarr[i].length - 1]]);
}

Here's a working fiddle to demonstrate.

Option 2 - ECMAScript 5 forEach()

// Create array to hold new values
var newArray = [];

// Loop through existing array and pull out data
myarr.forEach(function(obj) {
    newArray.push([obj[0], obj[obj.length - 1]]);
});

​Here's a working fiddle to demonstrate.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.