Reputation: 203
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
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
Upvotes: 1
Views: 41
Reputation: 1038
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);
}
Upvotes: 1
Reputation: 180
You can use toUpperCase() or toLowerCase() methods when doing the comparison.
for example:
let areEqual = str1.toUpperCase() === str2.toUpperCase();
Upvotes: 0
Reputation: 440
Instead of return
within array.every( .. )
use a counter. Then ..
return counter == array.length
Upvotes: 0