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}'
]
4
Answers
As you have created a data variable and then assigning it a value inside for loop so everytime the loop runs it overrides the last value. Instead create an array and push the values in that array.
I have update my answer to a more helpfull solution
In this example I store each laptop as an object and overwrite the toString() method.
Hope this helps.
You have some errors:
toSorted()
(sort()
mutates an array)gpu
andlaptop
since they are passed as arguments0
sofor(let i = 0
…data
should be an array and usepush()
to the array:There are some issues to the above snippet.
First of all you are passing in the arguments but you are using the
class variables. So if you intent to use the class variables there is no need to have arguments.
Secondly you treat
data
as a string thus it was assigning only the result of the last iteration.Third, you where starting your loop from position 1 thus first occurrences of both arrays are skipped.
Have a look at the below. Hope it helps you understand what the problems were