var arr = [{
name: "John Doe"
}, {
name: "jamal"
}, {
name: "Badr"
}, {
name: "mohsen"
}]
arr.forEach((val) => {
firstLetter = val.name.split(" ")[0].split("")[0];
});
for (var i = 0; i < arr.length; i++) {
if (firstLetter == "J" || firstLetter == "j") {
console.log("Goodbye " + arr[i].name);
} else {
console.log("Hello " + arr[i].name);
};
};
In your code, the firstLetter has only the last value in it m as you're overwriting its value.
Change the code to:
var arr = [{
name: "John Doe"
}, {
name: "jamal"
}, {
name: "Badr"
}, {
name: "mohsen"
}]
const firstLetter = [];
arr.forEach((val) => {
firstLetter.push(val.name.split(" ")[0].split("")[0]);
});
for (var i = 0; i < arr.length; i++) {
if (firstLetter[i] === "J" || firstLetter[i] === "j") {
console.log("Goodbye " + arr[i].name);
} else {
console.log("Hello " + arr[i].name);
};
};
If I understand correctly, you want to say "Goodbye " + val.name for names which start with J or j (and "Hello " + val.name for others). There's no need to do two loops for this (do the forEach or the for loop).
In any case, you can address the first character in the name as .name[0] and use comparison operators or String methods to determine if the name starts with a J or a j.
See the following code snippet for an example of this.
var arr = [{
name: "John Doe"
}, {
name: "jamal"
}, {
name: "Badr"
}, {
name: "mohsen"
}];
arr.forEach((val) => {
if (val.name[0] === "J" || val.name[0] === "j") {
console.log("Goodbye " + val.name);
} else {
console.log("Hello " + val.name);
}
});
You do not need an other loop after forEach, what you need is to check if the specific name starts with J/j
var arr = [{
name: "John Doe"
}, {
name: "jamal"
}, {
name: "Badr"
}, {
name: "mohsen"
}]
arr.forEach((val) => {
firstLetter = val.name.split(" ")[0].split("")[0];
if (firstLetter == "J" || firstLetter == "j") {
console.log("Goodbye " + val.name);
} else {
console.log("Hello " + val.name);
};
});