Spread Operator equivalent in IE - Javascript
Here is a simple way that could work on IE
data =[{name:"a"}, {name:"a"},{name:"x"}]
function getUniqueValues(array, prop) {
return array.map(function(item) { return item[prop]; })
.filter(function (item, index, self){ return self.indexOf(item) === index; }); // distinct
}
console.log(getUniqueValues(data, "name"))
The getUniqueValues there is performing two things for you; removing duplicated elements and also cloning the array. However, the map already is a clone of the array, so you just need to remove duplicates; you could use something like this:
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
function getUniqueValues(array, prop) {
function mapper(item) {
return item[prop];
}
return array.map(mapper).filter(onlyUnique);
}
I'd suggest you to take a look at stuff like webpack and babel in order to use the latest JS and also work on IE, by using transpiler and polyfills to generate compatible code ;)
PS. I don't have IE right now to test if filter works, but I'm pretty sure it does; otherwise you could remove duplicates by hand with a plain old for.
Your two syntaxes that you are asking about are the fat arrow for arrow functions and the spread operator. You can replace the former with a standard function expression and the latter with iteration using forEach
that adds the elements to an array. In addition, you also need a replacement for the Set
constructor that initializes it from an iterable. Instead, you need to add the elements one by one.
You can write your function like this. This first adds all values into a set, and then gets the values from the list and back to a new array:
function getUniqueValues(array, prop) {
// create set
var set = new Set();
array.forEach(function (item) {
set.add(item[prop]);
});
// convert set to array
var result = [];
set.forEach(function (item) {
result.push(item);
});
return result;
}
Since there is basic support for Set
, including forEach
, in Internet Explorer 11, you can use this without a polyfill.
Here is an example that runs fine in Internet Explorer 11:
var options = [
{ yypeOption: "option1" },
{ yypeOption: "option2" },
{ yypeOption: "option1" },
{ yypeOption: "option1" },
{ yypeOption: "option3" },
];
function getUniqueValues(array, prop) {
var set = new Set();
array.forEach(function (item) {
set.add(item[prop]);
});
var result = [];
set.forEach(function (item) {
result.push(item);
});
return result;
}
console.log(getUniqueValues(options, 'yypeOption'));