1

Folks I have a jquery function requirement that will compare two arrays.

listA = [' APPLE', 'banana', 'orange'] listB = [ 'BANANA ','appl']

ok so in above example, I need function to return "true". Basically what I need is a way to

  • Strip each word in both arrays to get rid of leading and trailing spaces.
  • Perform comparison which needs to be case insensitive.
  • Compare substring level, which means 'appl' does exist within ' APPLE', so it should be true

my code so far

<script> $(document).ready(function(){ Array.prototype.contains = function(array) { return array.every(function(item) { array = $.map(this, function(value){ return value.replace(/ /g, '').toUpperCase(); }); return array.indexOf(item.replace(/ /g, '').toUpperCase()) >= 0; }, this); } var result = [' APPLE', 'banana ', 'orange'].contains([ ' BANANA',' Appl ']); alert(result); }); 

so in above code example, it should return "true"

Any help is much appreciated

3 Answers 3

1

You can update the Array.prototype.contains function as below, this will remove the leading and trailing spaces and use a case insensitive comparison under the map function:

Array.prototype.contains = function(array) { return array.every(function(item) { var searchResult = this.map(function(i) { return i.trim().toLowerCase().indexOf(item.trim().toLowerCase()) >= 0; }); return searchResult.includes(true); }, this); } 
Sign up to request clarification or add additional context in comments.

Comments

0

Instead of return within array.every( .. )

use a counter. Then ..

return counter == array.length

Comments

0

You can use toUpperCase() or toLowerCase() methods when doing the comparison.

for example:

let areEqual = str1.toUpperCase() === str2.toUpperCase(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.