I'm sure I'm just missing something simple here, but I've hit a wall with this. I am attempting to run a loop through an array of names, and I want it to compare each name to the previous one to see if they are the same.
But what happens is as it goes through each name, it seems to be comparing it to itself, one character at a time, and going through a different character index each time.
Here is what I attempted:
var nameArray = ["Tony Stark", "Bruce Banner", "Bruce Banner", "Steve Rogers", "Steve Rogers"]
var nameComparisonArray = []
var element = ""
for (let index = 0; index < nameArray.length; index++) {
const name = nameArray[index]
const i = index
if (name != name[i - 1]) {
element = "" + name + " is different from " + (name[i - 1]) + ""
} else if (name == name[i - 1]) {
element = "" + name + " is the same as " + (name[i - 1]) + ""
}
nameComparisonArray.push(element)
}
console.log("nameComparisonArray", nameComparisonArray)
That returned this result:
[
"Tony Stark is different from undefined",
"Bruce Banner is different from B",
"Bruce Banner is different from r",
"Steve Rogers is different from e",
"Steve Rogers is different from v"
]
What I want it to return is this:
[
"Tony Stark is different from undefined",
"Bruce Banner is different from Tony Stark",
"Bruce Banner is the same as Bruce Banner",
"Steve Rogers is different from Bruce Banner",
"Steve Rogers is the same as Steve Rogers"
]
Anyone know how I can get my intended result? Any insight is appreciated!
Thanks!