4

Here diseaseList is an array .

for(var i=0;i<_list.length;i++)
{
    if($scope.diseaseList.indexOf(_list[i].disease) != -1){
        _list[i].favorite = true;
    }else{
        _list[i].favorite = false;
    }
}

I want to do somthing like this

if($scope.diseaseList.toLoweCase().indexOf(_list[i].disease.toLoweCase()) != -1){

but it is throwing error as $scope.diseaseList is an array .I can remove indexOf and use one more loop but that I dont want to do .Any other option please suggest.

Prashobh
  • 9,216
  • 15
  • 61
  • 91

1 Answers1

8

Arrays don't have toLowerCase (note that in your code there is a typo: missing r) function. But you can use the map function and return the lowercase values. It works like this:

["Foo", "BaR"].map(function (c) { return c.toLowerCase(); });
// => ["foo", "bar"]

In your code, this can be applied like below:

if($scope.diseaseList.map(function (c) {
    return c.toLowerCase();
   }).indexOf(_list[i].disease.toLowerCase()) != -1) { ... }

And additionally, you can remove != -1 and change it to use the bitwise operator:

if(~$scope.diseaseList.map(function (c) {
    return c.toLowerCase();
   }).indexOf(_list[i].disease.toLowerCase())) { ... }

@Tushar has another interesting solution for converting an array of strings to lowercase:

String.prototype.toLowerCase.apply(arr).split(',');
Community
  • 1
  • 1
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
  • 1
    Should be `return c.toLowerCase();` (note the extra `r` to `Lower`). – D4V1D Oct 06 '15 at 11:28
  • 2
    `String.prototype.toLowerCase.apply(arr).split(',');` Can also be used – Tushar Oct 06 '15 at 11:34
  • @Tushar Thanks. Added it to answer. :) Not sure how it works across the browsers (if I'm not wrong there were some problems on IE in stringifying arrays). But it's cute. – Ionică Bizău Oct 06 '15 at 11:37
  • @IonicăBizău You can also use `arr.map(String.prototype.toLowerCase.call.bind(String.prototype.toLowerCase));` See http://stackoverflow.com/questions/33006222/how-to-pass-the-method-defined-on-prototype-to-array-map-as-callback – Tushar Oct 08 '15 at 04:03