How to extract value from an array of array

前端 未结 6 1011
旧巷少年郎
旧巷少年郎 2021-01-29 03:32

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]]

相关标签:
6条回答
  • 2021-01-29 03:37

    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

    0 讨论(0)
  • 2021-01-29 03:38

    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]);
    }
    
    0 讨论(0)
  • 2021-01-29 03:44

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

    0 讨论(0)
  • 2021-01-29 03:44
    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/

    0 讨论(0)
  • 2021-01-29 03:48

    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(', '));
    
    0 讨论(0)
  • 2021-01-29 03:52

    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>

    0 讨论(0)
提交回复
热议问题