1

Let's say I have this Object of arrays:

foo = {morning: [1,2,3,4,5], afternoon: [1,2,3,4,7]}

I want to write a function that returns this object but remove a particular value.

ex: I want to remove the number 3 in afternoon. The function would return {morning: [1,2,3,4,5], afternoon: [1,2,4,7]}

myFunction = (partsOfDay, number) => {
  // do something
 // returns the object of arrays but without the specified value
}

How can I do that ?

Uj Corb
  • 1,411
  • 2
  • 17
  • 40
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array – hindmost Feb 27 '19 at 16:39
  • Thank you very much guys for your help :) although none of the duplicates mentioned are actual duplicates of my question... – Uj Corb Feb 27 '19 at 16:47

2 Answers2

2

You can do this without changing the source object using Array.reduce() and Object.entries().

The properties of the returned object will still point to the source object but the filtered array properties will be copied with Array.filter().

const foo = { morning: [1,2,3,4,5], afternoon: [1,2,3,4,7] };

const myFilter = (obj, prop, value) => Object.entries(obj).reduce((acc, [key, val]) => {
  acc[key] = key === prop && Array.isArray(val) ? val.filter(x => x !== value) : val;
  return acc;
}, {});

console.log(myFilter(foo, 'afternoon', 3));
console.log(myFilter(foo, 'morning', 3));
console.log(foo);
jo_va
  • 11,779
  • 3
  • 20
  • 39
0

There are many ways, something like this

var partsOfDay = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

myFunction = (partsOfDay, number) => {
  var filtered = partsOfDay.filter(function(value, index, arr){
    return value != number;
  });
}

Refer for more here

MyTwoCents
  • 6,028
  • 3
  • 18
  • 41
  • 2
    Where's the object (`foo` in the question) in your answer? – Federico klez Culloca Feb 27 '19 at 16:43
  • HI @MyTwoCents, thank you for your help, but the difficulty here is that it is an object of arrays, not just an array; and I need the function to return the whole object, but without the unwanted value. If I simply loop through both arrays to remove the `3` in `"morning"`, it will remove the `3` in both `"morning"` and `"afternoon"`. – Uj Corb Feb 27 '19 at 16:44