Javascript - Making Array Index toLowerCase() not working

I'm trying to make all array indexes lowercase strings, but it's not working. I looked at other answers on here and tried their solutions like using toString() before adding toLowerCase but it doesn't work, which is weird.

I created a jsfiddle of the problem here.

JS:

$(colorArr).each(function(i, item) // loop thru each of elements in colorArr and make lowercase + trim
{
    if(colorArr[i] !== undefined) // check if colorArr index undefined
      {
      colorArr[i].toString().toLowerCase().trim(); // FIX HERE
      /* TRIED - DIDN'T WORK!
      colorArr[i].toLowerCase().trim();
      */
       }
});

Answers:

Answer

i updated your fiddle

https://jsfiddle.net/af91r2cq/6/

colorArr[i] = colorArr[i].toString().toLowerCase().trim(); // FIX HERE

your way was really close ;)

Answer

You need to set the value back

It should be

colorArr[i] = colorArr[i].toString().toLowerCase().trim(); // FIX HERE

Or simply

colorArr = colorArr.map(function(value){ return value ? value.toLowerCase().trim() : ""; });
Answer

Another way change all defined values in the array to lowercase is to use the jQuery.map function like so:

colorArr = $.map(colorArr, function(item, i) {
  if(item !== undefined) {
    return item.toString().toLowerCase().trim();
  }
});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.