最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node.js create array of arrays - Stack Overflow

programmeradmin1浏览0评论

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 bine both variables in order to receive an array like this:

result = [['system1' , 'dev1'],['system1' , 'dev2'],['system1' , 'dev3']]

Thanks in advance!

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 bine both variables in order to receive an array like this:

result = [['system1' , 'dev1'],['system1' , 'dev2'],['system1' , 'dev3']]

Thanks in advance!

Share Improve this question asked Feb 27, 2020 at 15:21 benni0108benni0108 951 gold badge2 silver badges8 bronze badges 1
  • Have you attempted to implement yourself something that does this? – Romi Halasz Commented Feb 27, 2020 at 15:23
Add a ment  | 

4 Answers 4

Reset to default 7

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

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.

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;}

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.

发布评论

评论列表(0)

  1. 暂无评论