0

I have an array with this values:

0:
code: "fb"
description: "Not relevant text."
did: 1
name: "Some random name"
sortOrder: 1

1:
code: "fr"
description: "Not relevant text."
did: 2
name: "Some random name"
sortOrder: 2

When i map the array like this:

  values: this.stackOverflowExample.map(v => v.code).push(null)

And push a null code to the set, it sets all values to null

The output I want:

values: [
0: 'fb'
1: 'fr'
2: null ]

The output I got:

values: 3

How do I add values to the array this.stackOverflowExample which is mapped by code, without affecting the other values?

2
  • The Array.prototype.push method doesn't return the array it is called on. Rather, it returns the length of the array after adding the element. Either use a temporary variable, as in const a = this.stackOverflowExample.map(v => v.code).push(null); values: a` or to add the element using a method that returns the array such, i.e. Array.prototype.concat, as in values: this.stackOverflowExample.map(v => v.code).concat([null]) Commented Jun 2, 2021 at 12:19
  • @AluanHaddad Thank you for your answear with the concat method for the array , it does exactly what I wanted to achive. Commented Jun 2, 2021 at 12:38

1 Answer 1

8

The push method returns the new length of the array and not the mutated array, see documentation.

If you just want to append null to the mapped array you could either:

Concat your mapped array with [null]

values: anArray.map(mapFn).concat([null])

Spread your mapped array in an array with the last item being null

values: [...anArray.map(mapFn), null]
Sign up to request clarification or add additional context in comments.

2 Comments

Actualy this example returns: 0: (2) ['fb', 'fr'] 1: null Which is not exactly what i wanted to achive. The this.stackOverflowExample.map(v => v.code).concat([null]) from the comment returned the wanted output: 0: 'fb' 1: 'fr' 2: null But thanks anyway, for the explanation of the push method :)
You may have forgotten to spread your mapped array. .concat([null]) works too. I will update my answer to clarify this and add the other option.

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.