Skip to content
Advertisement

Array chain results in undefined

I have this array of strings, which is the result of a chain of array methods I’m implementing to a larger list. See the chain and array below:

["Coursing", "hunting", "guarding", "Hunting", "Guarding", "pulling", "Hauling", "Fighting", "flushing", "retrieving", "herding", "Herding", "Killing", "Trailing", "ratting", "Bolting", "droving", "Driving", "defending", "Flushing", "Accompanying", "Rat-baiting", "Retrieving", "holding", "trailing", "Luring", "Ratting", "fishing", "bolting", "Carrying", "Pulling", "Pointing", "racing"] 
    const initialFilter = this.props.dogs
                .map((dog) => dog.bred_for)
                .join(' , ')
                .split(' ')
                .filter((word) => {
                    return word.endsWith('ing');
                });

Now, when I apply the last method forEach(), which is supposed to turn the strings to lower case it prints undefined. Not sure why. see below the full chain.

        const initialDogsBreedForFilter = this.props.dogs
                .map((dog) => dog.bred_for)
                .join(' , ')
                .split(' ')
                .filter((word) => {
                    return word.endsWith('ing');
                })
                .forEach((word) => word.toLowerCase());

Any ideas why this might be happening?

Advertisement

Answer

forEach just iterates over the array. Returning from that doesn’t do anything. You should use map() here

const initialDogsBreedForFilter = this.props.dogs
                .map((dog) => dog.bred_for)
                .join(' , ')
                .split(' ')
                .filter((word) => {
                    return word.endsWith('ing');
                })
                .map((word) => word.toLowerCase());
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement