1

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

Stphane
  • 3,368
  • 5
  • 32
  • 47
Vianne
  • 548
  • 1
  • 10
  • 31

4 Answers4

4
  • 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; }
Ele
  • 33,468
  • 7
  • 37
  • 75
  • "A small group of characters, when they are converted to lowercase, cannot make a round trip. To make a round trip means to convert the characters from one locale to another locale that represents character data differently, and then to accurately retrieve the original characters from the converted characters." – Anar Sultanov Oct 09 '18 at 07:45
0

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);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
-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));
Fraser
  • 15,275
  • 8
  • 53
  • 104
-1

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

no need to case change testing the code

kishea
  • 637
  • 1
  • 6
  • 17