ad01012
ad01012

Reputation: 13

How to extract value from an array of array

I have an array of array stored. I need to extract the particular value from this arrays.

e.g allarray contain the list of arrays allarray= [Array[3],Array[3],Array[3]] are three arrays present in that.

0:Array[3] 0:"a1" 1:"b1" 2:"c1"

1:Array[3] 0:"a2" 1:"b2" 2:"c2"

3:Array[3] 0:"a3" 1:"b3" 2:"c3"

I need to extract this c1,c2 and c3 from the above arrays and display in the alert box.

Can anyone tell me how i can do that?

i tried with $.each but unfortunately doesn't work. Can anyone?

Upvotes: 0

Views: 202

Answers (6)

user4334903
user4334903

Reputation: 11

var arrOfArr=[['a1','b1','c1'],['a2','b2','c2'],['a3','b3','c3']];

var cVals=arrOfArr.map(function(element,index){
      return arrOfArr[index][2];
});
alert(cVals);

http://jsfiddle.net/3uaugbem/

Upvotes: 1

PeterKA
PeterKA

Reputation: 24638

var allarray = [
    ["a1", "b1", "c1"],
    ["a2", "b2", "c2"],
    ["a3", "b3", "c3"]
],
    num = 2;

//one by one
allarray.forEach(function( arr ) {
    alert( arr[ num ] );
});

//or all at once
alert( allarray.map(function( arr ) { return arr[ num ]; }).join(',') );

Upvotes: 1

MH2K9
MH2K9

Reputation: 12039

Can try using map(). Example:

var allarray = [["a1","b1","c1"],["a2","b2","c2"],["a3","b3","c3"]],
    index = 2;
allarray.map(function(val, ind){
    document.write(allarray[ind][index] + '<br />');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Upvotes: 1

Gaute L&#248;ken
Gaute L&#248;ken

Reputation: 7892

This is what the Array.prototype.map function is for:

var arr = [["a1","b1","c1"],["a2","b2","c2"],["a3","b3","c3"]];

var theValues = arr.map(function(inner) {return inner[2]});

alert(theValues.join(', '));

Upvotes: 1

Bijan
Bijan

Reputation: 8586

You can access it by running

allarray[X][2]

where X is 0, 1, or 2 depending on which of the 3 arrays you want

Upvotes: 0

Peter Olson
Peter Olson

Reputation: 142921

If I understand you correctly, your array looks like this

var allarray = [["a1","b1","c1"],["a2","b2","c2"],["a3","b3","c3"]];

To get c1, c2, and c3 you could just do this

 var c1 = allarray[0][2], c2 = allarray[1][2], c3 = allarray[2][2];

or you could do a loop to put all of the cs in a single array of its own

var cs = [];
for(var i = 0; i < allarray.length; i++) {
  cs.push(allarray[i][2]);
}

Upvotes: 2

Related Questions