Reputation: 578
This code gets rid of all the duplicate variables. Is there a way to make the array search in this function case insensitive?
var x = ["AAA", "aaa", "bbb", "BBB"];
function unique(list) {
var result = [];
$.each(list, function(i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});
return result;
}
// Output should be AAA, bbb
console.log(unique(x));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Associated JSFiddle here
Upvotes: 1
Views: 7506
Reputation: 1
Just add .toLowerCase to everything
var x = ["AAA", "aaa", "bbb", "BBB"];
function unique(list) {
var result = [];
$.each(list, function(i, e) {
if ($.inArray(e.toLowerCase(), result) == -1) result.push(e.toLowerCase());
});
return result;
}
alert(unique(x));
Upvotes: -1
Reputation: 637
just a little tweaking and you will be there
function unique(list) {
var result = [];
$.each(list, function(i, e) {
if($.inArray(e, list)){ result.push(e)};
});
return result;
}
that works fine
Upvotes: -1
Reputation: 33726
You don't need jQuery.
Use the function findIndex
and convert to lowerCase every element for each comparison.
var x = ["AAA", "aaa", "bbb", "BBB"];
function unique(list) {
var result = [];
list.forEach(function(e) {
if (result.findIndex(function(r) {
return r.toLowerCase() === e.toLowerCase();
}) === -1)
result.push(e);
});
return result;
}
console.log(unique(x))
.as-console-wrapper { max-height: 100% !important; top: 0; }
Using arrow functions:
var x = ["AAA", "aaa", "bbb", "BBB"];
function unique(list) {
var result = [];
list.forEach((e) => {
if (result.findIndex((r) => r.toLowerCase() === e.toLowerCase()) === -1)
result.push(e);
});
return result;
}
console.log(unique(x))
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 4
Reputation: 138257
You could use a lookuptable with only lowercase entries:
function unique(arr){
const before = new Set, result = [];
for(const str of arr){
const lower = str.toLowerCase();
if(!before.has(lower)){
before.add(lower);
result.push(str);
}
}
return result;
}
That in a oneliner:
const unique = arr => (set => arr.filter(el => (lower => !set.has(lower) && set.add(lower))(el.toLowerCase()))(new Set);
Upvotes: 0