0

I have the following function:

      var groceries = ["toothpaste", ["plums", "peaches", "pineapples"], ["carrots", "corn", "green beans"], "orange juice", ["chocolate", "ice cream"], "paper towels", "fish"];
      console.log("groceries", groceries);

      function removeItems(arr, toRemove) {
        function createKey(item) {
          return Array.isArray(item) ? item.join('-') : item;
        }

        var removeDict = toRemove.reduce(function(d, item) {
          var key = createKey(item);
          d[key] = true;

          return d;
        }, {});

        console.log("removeDict", removeDict);

        return arr.filter(function(item) {
          var key = createKey(item);

          return !removeDict[key];
        });
      }

      var result = removeItems(groceries, ["fish", "orange juice", ["chocolate", "ice cream"]]);

      console.log("result", result);

(This comes from this previous question I asked): function to remove single items or arrays from within an array - javascript

If I create a variable at the end that calls the function, it prints in the console correctly.

However, if I try to call the function directly, like this:

removeItems(groceries, ["fish", "orange juice", ["chocolate", "ice cream"]]);

console.log("groceries", groceries);

The items do not get removed. Why can't I call the function directly? Am I missing something?

1
  • 6
    because the function returns a new array, which you are discarding Commented Aug 30, 2017 at 6:30

1 Answer 1

1

The array filter method returns a new filtered array.

Therefore, your original array is not mutated.

If you store the result in a variable, you can then log that instead:

var newArr = removeItems(groceries, ["fish", "orange juice", ["chocolate", "ice cream"]]);

console.log("groceries", newArr)
Sign up to request clarification or add additional context in comments.

2 Comments

Got it. Thank you!
No problem. Glad this helped you out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.