Danny Heinrich
Danny Heinrich

Reputation: 21

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

Upvotes: 1

Views: 59

Answers (3)

TheMaster
TheMaster

Reputation: 50462

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)

Upvotes: 2

Ben Carey
Ben Carey

Reputation: 16958

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

Upvotes: 2

Harish
Harish

Reputation: 1911

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

Upvotes: 0

Related Questions