1

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 ]
2
  • You can skip the return statement in map's callback and remove curly brackets if only single expression is needed. Commented Apr 15, 2020 at 4:02
  • You have tagged your question with typescript2.0, which is for questions that apply only to TypeScript 2.0 and no other version of TypeScript, so for example not to TypeScript 1.8. You have also tagged your question with typescript1.8, which is for questions that apply only to TypeScript 1.8 and no other version of TypeScript, so for example not to TypeScript 2.0. Which of the two versions are you using? And why do you believe that your question only applies to that specific version? Are you aware that the versions you are using have been obsolete for over 3 years? Commented Apr 15, 2020 at 5:09

3 Answers 3

2

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)));

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

1

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.