A student of mine is trying to create a dropdown menu from a list that has multiple repeated values and wants it to display the unique, unrepeated values of the list.
Is there a way to filter a list to have just the unique values and then use that to make a dropdown menu? I don’t know what the command of setting unique values in a filtered list is.
you can use indexOf
or includes
depending on your use case
by using the base array with all of the repeating values iterating through it using a for
loop
var entries = ["a", "b", "a", "n", "c"];
var uniqueEntries = [];
for (var i = 0; i < entries.length; i++) {
if (!uniqueEntries.includes(entries[i])) {
uniqueEntries.push(entries[i]);
}
}
console.log(uniqueEntries);
this prototype call would probably be best in your use case because you do not need the index of where the entry is within the original array which is what indexOf
returns while includes
returns a boolean value if it exists within the array
Varrience
Thank you for responding. I just tried running this code and I get an error message that says that .includes is not a function. Is there another way of writing it?
oh yes that’s weird… well anyways indexOf will work i know it has that
var entries = ["a", "b", "a", "n", "c"];
var uniqueEntries = [];
for (var i = 0; i < entries.length; i++) {
if (uniqueEntries.indexOf(entries[i]) < 0) {
uniqueEntries.push(entries[i]);
}
}
console.log(uniqueEntries);
I’ve tested it on CDO i thought it did have the includes prototype but i guess it must have been an es6 prototype