I understand that there are ways to get unique elements in an array. This question isn't asking about that. This question is asking why indexOf
returns -1
for "kale" in the unique_vegetables
array once it's already been added. Is there something about indexOf
that makes it not work in this situation?
var vegetables = ["kale", "broccoli", "kale"];
function produce(){
var unique_vegetables = [];
unique_vegetables = vegetables.map(function(v){
if (v.length > 0){ //irrelevant check to make sure the string has characters
var k = unique_vegetables.indexOf(v);
return k < 0 ? v : null;
}else {
return null;
}
})
return unique_vegetables;
}
var t = produce();
console.log(t, "unique vegetables") /// ["kale", "broccoli", "kale"]