Need help understanding .map and .filter [Resolved]

Need help understanding .map and .filter [Resolved]
0

#1

I am trying to solve the below problem - I don’t necessarily want an answer, just some guidance to get me to think differently about what I’m doing wrong and why. I think I’m misunderstanding a key point in using .map and .filter functions, but I can’t find anything on the web to help.

Here’s the problem:

Task

Use Array#filter to write a function called getShortMessages.

getShortMessages takes an array of objects with ‘.message’ properties and returns an array of messages that are less than < 50 characters long.

The function should return an array containing the messages themselves, without their containing object.

Arguments

  • messages: an Array of 10 to 100 random objects that look something like this:

    {
    message: ‘Esse id amet quis eu esse aute officia ipsum.’ // random
    }

Conditions

  • Do not use any for/while loops or Array#forEach.
  • Do not create any unnecessary functions e.g. helpers.

Hint

  • Try chaining some Array methods!

My Solution

function getShortMessages(array){
array.
  filter(function( messages ){
    return array.message < 50;
  }).
  map(function( messages ){
    return array.message;
  })
}

I also tried using array.message.length thinking that was my issue, but I am getting an error “Cannot read property ‘length’ of undefined”. Makes sense because I’m getting undefined from my above solution, but why? I don’t understand how I can extract the object out of the array to find the length of the .message value. Any help would be appreciated! Thanks


#2

Try this:

function getShortMessages(array){
var newArray = array.filter(function(msg){
    return msg.message.length < 50;
  });
  return newArray;
}

#3

You’re trying to access the message parameter of the variable array, and then trying to get the length parameter of the non-existant message parameter. Let’s review what’s happening when you run an array function like .map():

  • You pass a function as a parameter to the .map() function. This function gets called on each of the array items in order.

  • This function is automatically passed a variable referencing the current item.

So, instead of array.message, you want to operate on the messages variable that gets passed into the function for each item in the array. Without seeing the data that you’re operating on, I’d have no idea what that variable would look like, but try this code to get a better idea of what’s happening:

array.filter(function(item) {
  console.log(item);
});

#4

This was the key point I was misunderstanding. Thank you!