Reputation: 12421
I came to know that in IE8 array filter function is not supported. After looking for help on internet I found this - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
It suggest that IE8 will work using above code.
HTML Code:
<body>
<a href="javascript:void(0)" onclick="calculateDiff()">Calculate</a>
</body>
JS Code:
function calculateDiff() {
var arr1 = new Array(1, 2, 3);
var arr2 = new Array(3, 4, 5);
var res = arr1.diff(arr2);
alert(res);
}
Array.prototype.diff = function(a) {
if(!Array.prototype.filter) {
alert("not supported");
Array.prototype.filter = function(fun) {
"use strict";
if(this == null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if(typeof fun != "function")
throw new TypeError();
var res = [];
var thisp = arguments[1];
for(var i = 0; i < len; i++) {
if(i in t) {
var val = t[i]; // in case fun mutates this
if (fun.call(thisp, val, i, t))
res.push(val);
}
}
return res;
};
}
else {
alert("supported");
return this.filter(function(i) {
return !(a.indexOf(i) > -1);
});
}
}
I have implemented the solution in this fiddle - http://jsfiddle.net/7LFMA/
What is wrong in the code? Why doesn't it work ?
Upvotes: 1
Views: 5233
Reputation: 664930
When running diff
for the first time, it will only alert "Not Supported"
, install the filter
polyfill but do nothing. It just returns undefined
, instead of diffing like it is supposed to do.
Remove the else
, or better just move the filter
installation outside the diff
function - it is not to be a part of it (e.g. in terms of closure, though modern engines will care about this).
Also, IE8 does not support the indexOf
method, you will need to put this compat shim in as well.
if (!Array.prototype.indexOf)
Array.prototype.indexOf = function (searchElement) {…};
if (!Array.prototype.filter)
Array.prototype.filter = function(fun) {…};
Array.prototype.diff = function(a) {
return this.filter(function(i) {
return !(a.indexOf(i) > -1);
});
};
function calculateDiff() {
var arr1 = new Array(1, 2, 3);
var arr2 = new Array(3, 4, 5);
var res = arr1.diff(arr2);
alert(res);
}
Upvotes: 3
Reputation: 178265
IE8 does not support indexOf for arrays - you still use it in the code so once you implement filter, it DOES exist and then IE8 will try to use indexOf.
In your code you do not actually APPLY the filter once you call DIFF but once you do that, you also need to implement indexOf
Upvotes: 1