peter flanagan
peter flanagan

Reputation: 9790

Map loop javascript in function not returning desired value

I have an array that contains objects that looks like this.

const arr = [
    {
        value: -1,
        label: "None"
    },
    {
        value: 24*60*60,
        label: "24 hours"
    },
    {
        value: 7*24*60*60,
        label: "7 days"
    },
    {
        value: 30*24*60*60,
        label: "1 month"
    },
    {
        value: 90*24*60*60,
        label: "3 months"
    }
];

I have the below function which 'kind of' works, but it is not returning the value. Can anyone spot what I am doing wrong?

The following is a react method

class Test extends Component { 

    ......

   getLabelFromValue(arr, value) {

      arr.forEach((item) => {

        if(item.value === value) {

            return item.label;

        }


    });

}

const value = getLabelFromValue(arr, 86400); //value is equal to undefined

Upvotes: 1

Views: 65

Answers (2)

Andreas
Andreas

Reputation: 21881

Callum Linington has already given a short explanation and solution how to solve the problem with your .forEach() construct.

Based on the code, getLabelFromValue should return a single value only.
Hence I would use another method of Array -> Array.prototype.find

"The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned."

getLabelFromValue(arr, value) {
    let item = arr.find(i => i.value === value);
    return item ? item.label : undefined /* or any other default value... */;
}

Upvotes: 2

Callum Linington
Callum Linington

Reputation: 14417

You're returning from the forEach not the outer function:

getLabelFromValue(arr, value) {
    let label;
    let done = false;

    arr.forEach(item => {

        if(item.value === value && !done) {

            label = item.label;

            done = true;

        }


    });

    return label;
}

const value = getLabelFromValue(arr, 86400); //value is equal to undefined

I would personally just use filter.

arr.filter(item => item.value === value)[0]; // OR
arr.find(item => item.value === value);

Upvotes: 2

Related Questions