using a map to apply some function into array

56 Views Asked by At

I am so new on typescript/javascript that I would like to modify each element of array with some function like following code. but I am wondering if there is a more concise/clear way to build my expected array from variable?

const variable  =  [1,2,3,4,5,6] 
function add(a: number, b: number): number {
  return a + b;
}
console.log(variable.map((i: number) => {return add(100, i)})) # =>[ 101, 102, 103, 104, 105, 106 ]
3

There are 3 best solutions below

0
palaѕн On BEST ANSWER

In ES6, if you have single expression as a return statement then you can simply re-write it as:

variable.map((i: number) => add(100, i))

Also, if you declare variable as an array of number like:

const variable: number[]  =  [1,2,3,4,5,6] 

Then inside .map() method you will not need to declare i: number as that would be automatically inferred. So, the .map() logic will become even more concise like:

variable.map(i => add(100, i))

Or, you can simply do it without using the add() function here:

variable.map(i => 100 + i)
0
Colin On

You don't really need to create an add function, you can directly add the number to current value during mapping.

const variable  =  [1,2,3,4,5,6] 

console.log(variable.map(num => num + 100))

0
Dacre Denny On

One semi-generic approach would be to define a function add(), which itself returns a function where the current item being mapped is added to the fixed amount specified (ie 100):

const add = (amount) => (item) => item + amount;

console.log([1,2,3,4,5,6].map(add(100)));