0

I have an array which has a list of items that will be returned as undefined if none come back and true if it does.

resolved = [undefined, undefined, undefined, true, undefined]

if there is a 'true' item in the Array how would I push it into a new array?

I have this so far.

resolved.map(item =>{

  if(item === undefined){
    console.log(`No resolved issues`);
  } else {
    console.log(`defined`);
  }

} )

output:

newResolved = [true]

resolved = [undefined, undefined, undefined, true, undefined]

resolved.map(item =>{
    
      if(item === undefined){
        console.log(`No resolved issues`);
      } else {
        console.log(`defined`);
      }
    
    } )

3
  • resolved.filter(Boolean)? resolved.some(Boolean)? Welcome to SO! Commented Oct 26, 2020 at 4:09
  • 2
    Unclear what you actually want. What is the output/other array? Commented Oct 26, 2020 at 4:09
  • @epascarello hey, just updated Commented Oct 26, 2020 at 4:11

3 Answers 3

1

You are using map() incorrectly as you need a return every iteration to the new array it creates

What you are really wanting is filter()

const arr = [undefined, undefined, undefined, true, undefined];

const res = arr.filter(e => e===true)

console.log(res)

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

1 Comment

.filter(Boolean)
1

You can use Array.prototype.filter function to filter valid items only.

const resolved = [undefined, undefined, undefined, true, undefined];

const result = resolved.filter(item => item);
console.log(result);

Comments

0

You're headed down the right path, I think. This looks like a prime use of the forEach method instead of the map method. This will allow you to look at each array value and do something with it.

const newArray = []

resolved.forEach(item =>{
  if(item === undefined){
    console.log(`No resolved issues`);
  } else {
    console.log(`defined`);
    newArray.push(item)
  }
})

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.