How to apply a callback to an array (apply a function to each element) in TypeScript

3 Answers

0 votes
// Using map() (returns a new array)

// with map() we transform arrays

// Callback: takes a number and returns a number
function double(x: number): number {
  return x * 2;
}

const numbers = [5, 10, 15, 20];

// Apply the callback to each element
const doubled = numbers.map(double);

console.log(doubled);



/*
run:

[10, 20, 30, 40] 

*/

 



answered Mar 21 by avibootz
0 votes
// Using forEach() (in‑place modification)

const numbers = [5, 10, 15, 20];

// Modify the array in place
numbers.forEach((value, index, arr) => {
  arr[index] = value * 2;
});

// With forEach() we do something with each element 
// rather than return a new array.

console.log(numbers);




/*
run:

[10, 20, 30, 40] 

*/

 



answered Mar 21 by avibootz
0 votes
// Using an inline arrow function as the callback

const numbers = [5, 10, 15, 20, 25];

const tripled = numbers.map(x => x * 3);

console.log(tripled);



/*
run:

[15, 30, 45, 60, 75] 

*/

 



answered Mar 21 by avibootz
...