Reputation: 95
I have a constant variable "client_id" and an array of variables called "device_list". For example:
client_id = "system1"
device_list = ['dev1' , 'dev2' , 'dev3']
Now i need to combine both variables in order to receive an array like this:
result = [['system1' , 'dev1'],['system1' , 'dev2'],['system1' , 'dev3']]
Thanks in advance!
Upvotes: 1
Views: 1611
Reputation: 210
a simple solution:
const client_id = "system1";
const device_list = ['dev1' , 'dev2' , 'dev3']
const result = device_list.map(device => [client_id, device]);
The map method is part of the array prototype.
It loops through every item in an array, and applies the given callback to each item.
For more information, I find the Mozilla docs extremely useful!: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Another thing to note: map is NON-mutative, meaning it doesn't affect the array on which it is called, it only returns a new one
Upvotes: 7
Reputation: 16993
You could do something like this using map:
const result = device_list.map(device => [client_id, device])
This will map your existing device_list
array to a new array, where each item consists of an array of client_id
and device.
Upvotes: 2
Reputation: 800
I'd go over a Array.prototype.map
here:
const result = device_list.map(function (item) { return [client_id, item]; })
It takes every element from device_list
and returns an Array instead. Those are collected into a new Array result
.
Upvotes: 1
Reputation: 73906
You can map
through the device_list
array and return a new array like this:
const client_id = "system1"
const device_list = ['dev1', 'dev2', 'dev3']
const result = device_list.map(d => [client_id, d])
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0;}
Upvotes: 1