Null isTrue
Null isTrue

Reputation: 1926

JavaScript Helper | startsWith( ) is not a function

I need to write a helper function that loops through an array of objects & filters all names that meet established criteria. In my case all names that begin with Zach

Array example:

const users = [
  {
    firstName: "Zach",
    id: 1,
    lastName: "Volsk"
  },
  {
    firstName: "Surly",
    id: 2,
    lastName: "Furious"
  },

  {
    firstName: "Zach",
    id: 3,
    lastName: "Tee"
  },
  {
    firstName: "Eve",
    id: 4,
    lastName: "Zelda"
  },

  {
    firstName: "Zachary",
    id: 5,
    lastName: "Toys"
  }
];

I'm able to retrieve the desired result applying filter and map directly i.e:

const filterZach = users
  .filter(user => user.firstName.startsWith("Zach"))
  .map(user => {
    return `<p>${user.firstName} ${user.lastName}</p>`;
  }).join(""); // get rid of comas

Desired Result: Zach Volsk, Zach Tee, Zachary Toys

However, when I tried to abstract that functionality into a helper method so that I can use it elsewhere in my code: i.e:

// helper
function filteredNames(arr, str) {
  return arr.filter(i => i.startsWith(str));
}

I get an error saying: i.startsWith is not a function

const filterZach = filteredNames(users, "Zach") // i.startsWith is not a function
const renderZach = filterZach.map(user => {
    return `<p>${user.firstName} ${user.lastName}</p>`;
  }).join("");

Question: Could you please help understand the reason for this issue showing me an alternative to accomplish my goal using a helper function?

I'm not married to the startsWith( ) method and I'd love to learn other ways to go about this. Reduce perhaps?

here's a code sandbox

Upvotes: 2

Views: 7973

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371203

Inside filteredNames, with arr.filter(i, i is an object, not a string, and objects don't have a startsWith method. Reference the object's firstName instead, and call startsWith on it:

// helper
function filteredNames(arr, str) {
  return arr.filter(i => i.firstName.startsWith(str));
}

const users = [
  {
    firstName: "Zach",
    id: 1,
    lastName: "Volsk"
  },
  {
    firstName: "Surly",
    id: 2,
    lastName: "Furious"
  },

  {
    firstName: "Zach",
    id: 4,
    lastName: "Tee"
  },
  {
    firstName: "Eve",
    id: 5,
    lastName: "Zelda"
  },

  {
    firstName: "Zachary",
    id: 6,
    lastName: "Toys"
  }
];
// helper
function filteredNames(arr, str) {
  return arr.filter(i => i.firstName.startsWith(str));
}
const filterZach = filteredNames(users, "Zach") // i.startsWith is not a function
const renderZach = filterZach.map(user => {
    return `<p>${user.firstName} ${user.lastName}</p>`;
  }).join("");
document.body.innerHTML += renderZach;

For a dynamic property name to call startsWith on, pass that property name to filteredNames, eg

function filteredNames(arr, str, prop) {
  return arr.filter(i => i[prop].startsWith(str));
}

Upvotes: 5

Related Questions