Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spread Operator equivalent in IE - Javascript

Tags:

javascript

I have a javascript function to populate dropdowns for individual table rows like:

$scope.possibleOptions = getUniqueValues($scope.yypeOptions, 'yypeOption')
    .map(function(id) {
            return {
                id: id,
                name: id
            });

function getUniqueValues(array, prop) {
    return [...new Set(array.map(item => item[prop]))];
}

where, $scope.yypeOptions is:

$scope.yypeOptions = [{
    yypeOption: "option1"
}, {
    yypeOption: "option2"
}];

I now have to make it compatible to IE. The spread and => operator is something I have to replace.

Went through this and this link. But I could not get any understanding how to replace the Set inside an Array feature.

like image 365
Mike Avatar asked Feb 11 '19 16:02

Mike


2 Answers

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"))
like image 200
Alen.Toma Avatar answered Nov 12 '22 19:11

Alen.Toma


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.

like image 3
Luan Nico Avatar answered Nov 12 '22 20:11

Luan Nico