Home > database >  Array methods returning undefined
Array methods returning undefined

Time:11-01

This is something I still don't quite understand very well, I have the following situation:

// #2) Check if this array includes any name that has "John" inside of it. If it does, return that 
// name or names in an array. 
const dragons = ['Tim', 'Johnathan', 'Sandy', 'Sarah'];

at first I tried the following:

const name = dragons.forEach(element => {
    element.includes("John") ? element : null
});

it returns undefined

then:

const name = dragons.filter(element => {
    element.includes("John");
});

it returns an empty array

then:

function name() {
    const dragons = ['Tim', 'Johnathan', 'Sandy', 'Sarah'];
    dragons.forEach(element => {
        if (element.includes("John")) {
            return element;
        }
    });
}

again it returns undefined

but the interesting thing is that if on any of the attempts I change the action to do to console.log(element); then it will show "Johnathan" which is the correct output.

so it means that the logic is working, I just don't understand why it won't return the value if I want to let's say assign it to a variable.

I even tried the following:

const dragons = ['Tim', 'Johnathan', 'Sandy', 'Sarah'];

dragons.forEach(element => {
    if (element.includes("John")) {
        const name = element;
    }
});

but it again returns name as undefined, why is that?

edit: this was my first stack overflow question, really I wasn't expecting someone answering my question, I thought maybe it was a dumb question or that i didn't explained myself well but it was very nice to find such a supportive community, thank you so much to all of you who commented and helped me!

CodePudding user response:

forEach method does return undefined. But filter instead returns the array but filtered. However, the problem is that you are forgetting to return the values inside it.

To fix it try:

const name = dragons.filter(element => {
  return element.includes("John");
});

Or:

const name = dragons.filter(element => element.includes("John"));

CodePudding user response:

First, forEach never returns anything. You'd need a map for that, or filter (what are you exactly after?). Second, your callback functions don't return anything, either. You can map or filter your array like that:

const dragonsNamedJohn = dragons.filter(name => name.includes('John'));

or

const dragonsNamedJohn = dragons.filter(name => {
    return name.includes('John'); 
});

or even

function hisNameIsJohn (name) {
    return name.includes('John');
}

const dragonsNamedJohn = dragons.filter(hisNameIsJohn);

(You might want to stick toLowerCase() somewhere there, or not, dependent on whether you want the comparison to be case-sensitive. Also, another way of skinning a dragon would be to use a regular expression).

  • Related