Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript function looping array

Why can’t I get the output I want, I tried various ways but it doesn’t work, where is it wrong?

Give me a clue so I can learn.

let laptop = ["asus", "lenovo", "acer", "hp", "axioo"];
let gpu = [4070, 4090, 4050, 4080, 4060];

const laptopGpu  = (device, gra) => {
  device = laptop.sort()
  gra = gpu.sort()
  let data = ""
  for(let i = 1; i < device.length; i++) {
    data = `{${device[i]} with gpu ${gra[i]}}`
  }
  return new Array (data)
}
console.log(laptopGpu(laptop,gpu));

This is the output I want:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[ 
  '{acer with gpu 4050}',
  '{asus with gpu 4060}',
  '{axioo with gpu 4070}', 
  '{hp with gpu 4080}',
  '{lenovo with gpu 4090}'
]

>Solution :

You have some errors:

  1. Don’t mutate arguments passed, so use rather toSorted() (sort() mutates an array)
  2. Don’t use the global gpu and laptop since they are passed as arguments
  3. JS arrays starts with 0 so for(let i = 0
  4. Your output is array so data should be an array and use push() to the array:
let laptop = ["asus", "lenovo", "acer", "hp", "axioo"];
let gpu = [4070, 4090, 4050, 4080, 4060];

 
const laptopGpu  = (device, gra) => {
    device = device.toSorted()
    gra = gra.toSorted()

    let data = [];

    for(let i = 0; i < device.length; i++) {
       data.push(`{${device[i]} with gpu ${gra[i]}}`);
    }

    return data;
}

console.log(laptopGpu(laptop,gpu));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading