0

I have a map like this:

and I want to remove {frequency:"WN"} from array inside map value.

I am trying to remove it this way but value isn't getting removed:

const map2 = new Map();
map2.set(0, [{frequency:"DN"},{frequency:"WN"}, {frequency:"KK"}]);
map2.set(1, [{frequency:"DN"},{frequency:"WN"}, {frequency:"KK"}]);

const strNanFrq = ['DN', 'WN', 'MN', 'QN', 'YN'];
for (tsRequest of map2.values()) {
  tsRequest.filter((req, index) => {
    if (strNanFrq.includes(req['frequency'])) {
      tsRequest.splice(index, 1);
    }
  });
}

console.log(Array.from(map2.values())); // still has all the values in map
adiga
  • 34,372
  • 9
  • 61
  • 83
kittu
  • 6,662
  • 21
  • 91
  • 185

2 Answers2

1

You can loop through the Map and filter each value to remove the objects with frequency included in the strNanFrq. Create a Set for strNanFrq and check if the set has the current object's frequency.

const map = new Map([
  [0, [{ frequency:"DN" },{ frequency:"WN" }, { frequency:"KK" } ]],
  [1, [{ frequency:"YN" },{ frequency:"AA" }, { frequency:"BB" } ]],
]);

const strNanFrq = new Set(['DN', 'WN', 'MN', 'QN', 'YN']);

for (const [key, value] of map)
  map.set(key, value.filter(v => !strNanFrq.has(v.frequency)))

console.log(map.get(0))
console.log(map.get(1))
adiga
  • 34,372
  • 9
  • 61
  • 83
-1

Set again the map value with a filtered array of the previous array. If there are more array in the map just use forEach to loop through maps key-value pairs and check if the value is actually an array and reset it with filter:

var map2 = new Map();

map2.set(0, [{frequency:"DN"},{frequency:"WN"}, {frequency:"KK"}]);
map2.set(1, [{frequency:"DN"},{frequency:"WN"}, {frequency:"KK"}]);


map2.forEach((val, key) => {  
  if (Array.isArray(val)) {
      map2.set(key, val.filter(el => el.frequency !== 'WN'));
  }
});

console.log(map2.values());
arm
  • 145
  • 1
  • 5
  • I may have more number of keys – kittu Dec 05 '19 at 07:10
  • You can have more arrays which contain objects with property `frequency` and want to remove from each frequencies that have a value of `WN`? – arm Dec 05 '19 at 07:13