1

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
8
  • You array is not valid. is value a String ? Commented Mar 10, 2017 at 9:04
  • 1
    getLabelFromValue(arr, value) { should be function getLabelFromValue(arr, value) { Commented Mar 10, 2017 at 9:05
  • You are using forEach and not map and not returning anything frm getLabelFromValue? Commented Mar 10, 2017 at 9:05
  • What do you need as the output ? Commented Mar 10, 2017 at 9:06
  • @lonut it depends if the extract was taken from a class Commented Mar 10, 2017 at 9:06

2 Answers 2

2

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... */;
}
Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.