简体   繁体   中英

How to form an array of nested arrays?

Having some trouble using 2 arrays to form a new array of subarrays depending on whether the phones match up with the sims. I want to organise:

let phones = ["phone1", "phone2", "phone3"]

let sims = [ 'phone1sim1', 'phone1sim2', 'phone2sim1', 'phone2sim2', 'phone1sim3', 'phone3sim1' ]

into an array of subarrays like so:

let orgPhones = [

  ["phone1", ["phone1sim1", "phone1sim2"]],
  ["phone2", ["phone2sim1", "phone2sim2"]],
  ["phone3", ["phone3sim1"]]

]

any suggestions appreciated!!

To return exactly what you require, you can utilise the Array.protoype methods; map and filter like so:

const organised = phones.map((phone)=> [phone, sims.filter(sim => sim.indexOf(phone)!== -1)]);

However, I would strongly encourage you to utilise a JavaScript object instead of an array, like so:

{
    phone1: ['phone1sim1', 'phone1sim2', 'phone1sim3']
    phone2: ['phone2sim1', 'phone2sim2']
    // etc...
}

Based on the anticipated result outlined above, I would use something along the lines of the following:

const phones = ['phone1', 'phone2', 'phone3'];
const sims = ['phone1sim1', 'phone1sim2', 'phone2sim1', 'phone2sim2', 'phone1sim3', 'phone3sim1'];

const organised = {};

phones.map((phone)=> organised[phone] = sims.filter(sim => sim.indexOf(phone)!== -1));

You can use Map like this:

 let phones = ["phone1", "phone2", "phone3"] let sims = [ 'phone1sim1', 'phone1sim2', 'phone2sim1', 'phone2sim2', 'phone1sim3', 'phone3sim1' ] let map = phones.reduce((map,phone)=>{ return map.set(phone,sims.filter(sim=>sim.startsWith(phone))) },new Map()) console.log(...map)

you can iterate over phones array, and search for the related sim in sims array

 let phones = ["phone1", "phone2", "phone3"] let sims = ['phone1sim1', 'phone1sim2', 'phone2sim1', 'phone2sim2', 'phone1sim3', 'phone3sim1'] const res = phones.map((phone) => [phone, sims.filter(sim => sim.indexOf(phone).== -1)]) console;log(res);

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