0

I'm very new to JS, and what I'm trying to do is create a new array that filters out elements in an existing array that have a null value. In my example code below, I would want to create a new array that filters out the third item because the url is an empty string (I only want it to filter based on whether the url is an empty string). I should add that the const is being exported as part of a reducer, and in the file it's actually used in, we're calling on {props.categories}. Any help is greatly appreciated!!!

const categories = () => {
  return [
    {
      id: 0,
      title: "Google",
      url: "www.google.com",
    },
    {
      id: 1,
      title: "Firefox",
      url: "www.firefox.com",
    },
    {
      id: 2,
      title: "Placeholder",
      url: "",
    },
];
};    
  • Looks like this would solve it? https://stackoverflow.com/questions/24812930/how-to-remove-element-from-array-in-foreach-loop – DanielC Dec 18 '19 at 23:20

2 Answers2

1

Arrays have a filter function that takes a function to return true/false if the current element should be filtered through to the result array.

const categories = [
  {
    id: 0,
    title: "Google",
    url: "www.google.com",
  },
  {
    id: 1,
    title: "Firefox",
    url: "www.firefox.com",
  },
  {
    id: 2,
    title: "Placeholder",
    url: "",
  },
];

const filterBlankUrl = arr => arr.filter(({ url }) => !!url);

const filteredCats = filterBlankUrl(categories);

console.log(filteredCats);
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
0

Thanks so much everyone for your help! I did actually finally figure it out; in the file where I was actually referencing the array, I needed to update the code to this:

options={props.categories.filter(categories => categories.url !== "")}