0

How can I return the first values from a set of arrays?

var arr = [
    ['2009', 1000, 400, 800],
    ['2010', 1170, 460, 1200],
    ['2011', 660, 1120, 500],
    ['2012', 1030, 540, 800]
], res, i, a, b, c, d, e;

!function doMerge() {
    for(i = 0; i < arr.length; i++) {
        res = arr[i];       
        console.log(res.splice(1));
    }    
}(arr)

// get rid of years
// prints    
[1000, 400, 800] 
[1170, 460, 1200] 
[660, 1120, 500] 
[1030, 540, 800] 

I'm trying to build an array of the first of these values [1000, 1170, 660, 1030]

3 Answers 3

1
res = [];

function doMerge() {
    for(i = 0; i < arr.length; i++) {
        res.push(arr[i][1]);       
    }    
}

doMerge();

console.log(res);

outputs [ 1000, 1170, 660, 1030 ]

Sign up to request clarification or add additional context in comments.

4 Comments

Where is [1000, 1170, 660, 1030] produced by this?
it is in the res variable; this was the minimal change from original code. I would have returned the new array from the function.
You have a syntax error on line 3 (an unmatched {) and even after fixing, I don't think res becomes what you think it becomes (try it and see)
remove console.log with splice, I missed that.
1
var arr = [
    ['2009', 1000, 400, 800],
    ['2010', 1170, 460, 1200],
    ['2011', 660, 1120, 500],
    ['2012', 1030, 540, 800]
];

var newArr = [];

for (var x = 0; x < arr.length; x++){
  newArr.push(arr[x][1]);
}

console.log(newArr);

Here is a solution.

http://jsfiddle.net/wcVZH/

Comments

0

If you don't want a for or while loop you can one line this with Array.prototype.map

var myArr = arr.map(function (a) {return a[1];});

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.