0

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?

3
  • 1
    post a jsfiddle of what you have done so far Commented Dec 7, 2014 at 17:42
  • You need a loop within a loop. Commented Dec 7, 2014 at 17:42
  • You want usually get the 3rd element of each array ? Commented Dec 7, 2014 at 17:42

6 Answers 6

2

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]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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(', '));

Comments

1

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>

Comments

1

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(',') );

Comments

1
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/

Comments

0

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

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.