Reputation: 11
how do I want to fill the undefined value in the seats array with the value in namaPenumpang
my code
I have tried using a for
loop it worked
var kursi = [undefined, "galih"];
function tambahPenumpang(namaPenumpang, kursi) {
// jika angkot masih kosong
if (kursi.length == 0) {
kursi.push(namaPenumpang);
return kursi;
} else {
for (let i = 0; i < kursi.length; i++) {
if (kursi[i] === undefined) {
kursi[i] = namaPenumpang;
return kursi;
} else if (namaPenumpang === kursi[i]) {
console.log("Kursi ini sudah terisi oleh " + kursi[i]);
return kursi;
} else if (kursi[i] !== undefined) {
kursi.push(namaPenumpang);
return kursi;
}
}
}
}
How my code work use a map()
?
Please help me to solve this problem, how can the contents of the array at the index with the value unndefined be replaced using the value namaPenumpang
Upvotes: 0
Views: 47
Reputation: 1
You can get the same functionality with the map function.
var kursi = [undefined, "galih"];
function tambahPenumpang(namaPenumpang, kursi) {
kursi = kursi.map((penumpang) => {
if (penumpang === undefined) {
return namaPenumpang;
} else {
return penumpang;
}
});
return kursi;
}
Upvotes: 0
Reputation: 265
map
always returns an array of the same size. So you cannot add new items.
The logic of your code probably does not do what you intend.
Here are some modifications:
let arr = ["x", undefined, "z"];
function tambahPenumpang(namaPenumpang, kursi) {
// it is confusing to modify the original array and return it
// so we create a new array and leave the original array untouched
const newArr = [...kursi];
if (newArr.includes(namaPenumpang)) {
console.log("Kursi ini sudah terisi oleh " + namaPenumpang);
return newArr;
}
for (let i = 0; i < newArr.length; i++) {
if (newArr[i] === undefined) {
newArr[i] = namaPenumpang;
return newArr;
}
}
// if we reach here, then it was not added
newArr.push(namaPenumpang);
return newArr;
}
arr = tambahPenumpang("x", arr); // Kursi ini sudah terisi oleh x
console.log(arr); // ["x", undefined, "z"]
arr = tambahPenumpang("y", arr);
console.log(arr); // ["x", "y", "z"]
arr = tambahPenumpang("a", arr);
console.log(arr); // ["x", "y", "z", "a"]
Upvotes: 0