Search code examples
javascriptarraysfunctionloops

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:

[ 
  '{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 an 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));