简体   繁体   中英

Return undefined on Array.map

I don't want this map to return undefined how can i do that ?

var onCompareSelectedClick = function () {
            var talentProfileInfoForAppliedResources = appliedResourcesEntries.map(function(res) {
                console.log(res);
                if(res.compareSelected == true) {
                    return data.getTalentProfileInfo(res.RES.RES_ID);
                }
            });
            console.log(talentProfileInfoForAppliedResources);
            this.openCompareTPDlg(talentProfileInfoForAppliedResources);
        }.bind(this);

Just add else statement inside map method returning needed value, like:

if(res.compareSelected == true) {
   return data.getTalentProfileInfo(res.RES.RES_ID);
} else {
   return 'default_value';
}

TL;DR

Use the Array.filter method after Array.map to remove undefined elements in the new array.


Expanding on @Bloomca's answer:

As stated in the documentation provided here .

The map() method creates a new array with the results of calling a provided function on every element in this array.

Hence the reason why your new array contains undefined elements is because you are not explicitly calling return within the function on some elements that are called using the provided function. In Javascript, not explicitly calling return will nevertheless return undefined .

For example, in the following method newArray will be set to the logged result:

[ undefined, 2, 3 ]

newArray = [1,2,3].map(function(elem) { if (elem > 1) return elem })
console.log(newArray)

This is why the answer provided above will no longer result in undefined elements within the new array. The conditional will resolve if the condition res.compareSelected == true is not true to the return statement within the else block (note that you could simply remove the true here and simply put res.compareSelected which would be better practice).

Based on your question you may find using the Array.filter method to return an Array without the undefined values. And with only the values on which you have called the function data.getTalentProfileInfo(res.RES.RES_ID) .

You could do this in the following manner:

var onCompareSelectedClick = function () {
    var arr = appliedResourcesEntries.map(function(res) {
        if(res.compareSelected == true) {
            return data.getTalentProfileInfo(res.RES.RES_ID);
        }
    });
    var talentProfileInfoForAppliedResources = arr.filter(function(elem) {
        return elem;
    });
console.log(talentProfileInfoForAppliedResources);
this.openCompareTPDlg(talentProfileInfoForAppliedResources);
}.bind(this);

You can read about the Array.filter method here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM