0

I was trying to create new array which will get elements from "serie" array. I want to remove elements smaller than 10 and multiply elements bigger than 10. I can do this by creating two separate variables with using filter(), but is it possible to do it with a single variable and a function like only using map() or forEach()?

Is there a method which the elements in the map() be thrown directly in a way like element.pop() so this particular element will be deleted without empty array while mapping elements. So for this code I can remove the element if it is lower than 10 and multiply it if it is bigger than 10

let serie = [7,4,9,12,18,21];

var newSerie = serie.map(function(element){

    
  if(element>10) {
   return element*10;
  }else{
    return element;
  }
  
    if(element<10){
    newSerie.splice(serie.indexOf(element),1); 
  }
  

})

console.log(newSerie);
  • 1
    what about `reduce`? see [example](https://stackoverflow.com/a/24806827). – Bagus Tesa Apr 10 '22 at 10:14
  • As @BagusTesa recommended [`reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) returns an arbitrary result (whereas `map` always returns an array of the same length as that it was called on) `const newSerie = serie.reduce((a, element) => (element > 10 ? [...a, element * 10] : a), []);` alternatively just use a `for` loop. – pilchard Apr 10 '22 at 10:19
  • 1
    You should use combination of `.filter()` and `.map()`. Even though this is slightly less performant, it is _significantly_ more readable than any other approach. – Parzh from Ukraine Apr 10 '22 at 10:32
  • 1
    Pro tip: use `.reduce()` only when there's no other way. – Parzh from Ukraine Apr 10 '22 at 10:32

1 Answers1

1

Use .filter to remove elements, then apply needed action on them using .map

let serie = [7, 4, 9, 12, 18, 21];

const result = serie.filter(x => x > 10).map(x => x * 10)
console.log(result)

Or in one go using .reduce

const result = serie.reduce((acc, x) => {
  if (x >= 10) {
    acc.push(x * 10)
  }
  return acc;
}, []);
EugenSunic
  • 13,162
  • 13
  • 64
  • 86