简体   繁体   中英

JavaScript - How to make an array of values out of an key and value array

I have the next key:value array -

[["key1",76],["key2",73],["key3",59],["key4",52],["key5",37],["key6",7],["key7",5],["key8",5],["key9",3],["key10",2],["key11",2]]

And I would like to make an array out of it but only with the values of it and also to keep the order of the values, meaning the new array should be like this -

[76,73,59,52,37,7,5,5,3,2,2]

I've tried to find a way to do that but failed miserably,

Thanks in advanced for any kind of help

You can use map :

var arr1 = [["key1",76],["key2",73],["key3",59],["key4",52],["key5",37],["key6",7],["key7",5],["key8",5],["key9",3],["key10",2],["key11",2]];
var arr2 = arr1.map(function(v){ return v[1] });

 var arr = [["key1",76],["key2",73],["key3",59],["key4",52],["key5",37],["key6",7],["key7",5],["key8",5],["key9",3],["key10",2],["key11",2]]; var result = []; arr.forEach(function(val,index){ result.push(val[1]); }); alert(JSON.stringify(result)); 

var res_list = [];
var ori_list = [["key1",76],["key2",73],["key3",59],["key4",52],["key5",37],["key6",7],["key7",5],["key8",5],["key9",3],["key10",2],["key11",2]];

for( var i=0, len=ori_list.length; i<len; i ++ ) {
    res_list.push( ori_list[i][1] );
}

No need of looping through the array, you can use regex in your case to extract all the values from the nested array.

 var target = [["key1",76],["key2",73],["key3",59],["key4",52],["key5",37],["key6",7],["key7",5],["key8",5],["key9",3],["key10",2],["key11",2]]; var result = target.toString().match(/\\b\\d+\\b/g); console.log(result); document.write(result); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM