0

Why is the below returning undefined? Shouldn't I just get back [{name:'bug']?

var a= [{name:'dark'},{name:'bug'}]

a.map(function (obj) {
    if (obj.name !== 'dark'){
      return obj
    }
  })

//returns [undefined,{name:'bug}]
1
  • 2
    I think you're sort of confusing map with filter. Commented Aug 28, 2016 at 6:18

2 Answers 2

3

.map means you are mapping something for every item in an array. If you do not return anything, it will return undefined

If you wish to get certain values based on condition, you should use .filter

var a = [{
  name: 'dark'
}, {
  name: 'bug'
}]

var b = a.filter(function(obj) {
  return obj.name !== 'dark'
})

console.log(b)

Usage

  • Map: if you wish to get some property of an object from an array of objects.
  • Filter: If you wish to get specific values based on a condition. This will return array.
  • Find: If you wish to get only first matching value. This will return element and not array.
  • forEach: If you wish to loop over array and do specific processing.

Note: Most of array functions have compatibility issues and you should check it before using it.

References

  • map: The map() method creates a new array with the results of calling a provided function on every element in this array
  • Filter: The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Sign up to request clarification or add additional context in comments.

7 Comments

so there's no way to remove something from an arr with map? I should just use forEach and pop?
No. And it is not intended for this. If you wish to remove values, use Array.filter
@mangocaptain In general, you should not think in terms of "removing something from an array". You will end up splicing and slicing and popping and just confusing yourself. It's almost always better to think of creating a new array with just the elements you want, which is exactly what filter does.
Nevertheless, you could just insert a splice line in a forEach statement to remove a chosen object
What compatibility issues?
|
0

you can use filter like this :

var a= [{name:'dark'},{name:'bug'}];
var b = a.filter(item => item.name != 'dark');
console.log(b); // [ { name: 'bug' } ] 

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.