I have got a list of stocks inside a array . Each Stock belongs to a Sector , For example
CBB , VZ belongs to Communications Sector
UPS , RRTS belongs to Transportation Sector
AAC belongs to Health Sector
When i am looping through the array , the output is
CBB
VZ
UPS
RRTS
AAC
I am in requirement to display it this way
CBB Communications
VZ Communications
UPS Transportation
RRTS Transportation
AAC Health
My Code
$(document).ready(function() {
var list_of_stocks= [
"CBB",
"VZ",
"UPS",
"RRTS",
"AAC "
]
for(var i=0;i<list_of_stocks.length;i++)
{
console.log(list_of_stocks[i]);
}
});
/ with the above code
How to maintain a another key value pair list structure to achieve this efficiently
(I don't want the array list_of_stocks to be modified) , so want to create another key value pair list . Thank you for reading this
I have got a list of stocks inside a array . Each Stock belongs to a Sector , For example
CBB , VZ belongs to Communications Sector
UPS , RRTS belongs to Transportation Sector
AAC belongs to Health Sector
When i am looping through the array , the output is
CBB
VZ
UPS
RRTS
AAC
I am in requirement to display it this way
CBB Communications
VZ Communications
UPS Transportation
RRTS Transportation
AAC Health
My Code
$(document).ready(function() {
var list_of_stocks= [
"CBB",
"VZ",
"UPS",
"RRTS",
"AAC "
]
for(var i=0;i<list_of_stocks.length;i++)
{
console.log(list_of_stocks[i]);
}
});
http://jsfiddle/n3fmw1mw/202/ with the above code
How to maintain a another key value pair list structure to achieve this efficiently
(I don't want the array list_of_stocks to be modified) , so want to create another key value pair list . Thank you for reading this
Share Improve this question edited Jul 29, 2016 at 13:49 JJJ 33.2k20 gold badges94 silver badges103 bronze badges asked Jul 29, 2016 at 13:27 PawanPawan 32.4k109 gold badges268 silver badges447 bronze badges 02 Answers
Reset to default 5You can use javascript object:
var list_of_stocks= {
"CBB": "Communications",
"VZ": "Communications",
"UPS": "Transportation",
"RRTS": "Transportation",
"AAC": "Heath"
};
for (var key in list_of_stocks) {
if (list_of_stocks.hasOwnProperty(key)) {
console.log(key + " -> " + list_of_stocks[key]);
}
}
See http://jsfiddle/n3fmw1mw/204/
Why don't you use an object to do this?
obj = {
munications: ['CBB', 'VZ'],
transportation: ['UPS', 'RRTS'],
health: ['AAC']
}
or and multidimensional array
newArr = [['CBB', 'VZ'],['UPS', 'RRTS'],['AAC']]
then you know that newArr[0] will have the Communications array and so on.