Skip to content
Advertisement

How to create a nested list by sending data from a function

I have the next code:

let dataList = [];

function filli(index, name, words){
    dataList[index] = index;
    dataList[index] = name;
    dataList[index] = words;
}

filli(0, "David", "Testing this")
filli(1, "John", "My cellphone")
console.log(dataList)

I get in console the next:

$ node attempt.js
[ 'Testing this', 'My cellphone' ]

And my expected output in console would be:

[[0, "David", "Testing this"], [1, "John", "My cellphone"]]

But I don´t get that in console, as you can see I was trying to get that data in my filli function, sending an index, name, and words but it doesn’t work.

I hope you can help me, thank you.

Advertisement

Answer

You are overriding existing values when you do dataList[index]= .... You need to add them as an array, something like this:

let dataList = [];

function filli(index, name, words){
    dataList[index] = [index, name, words];
}

filli(0, "David", "Testing this")
filli(1, "John", "My cellphone")
console.log(dataList)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement