1

I need to return an empty array if obj.chk != true to check if no checked toDos

function listChk() 
{
    if (!chkExist('./toDoArr')) {console.log('Please create toDo list first!')}
    else {

        let toDoArr = JSON.parse(fs.readFileSync('./toDoArr'))

        let chkToDoArr = toDoArr.map(function (obj) {
            if (obj.chk === true){
               console.log( obj.toDo)
               return obj.toDo
            }
        });
        console.log(chkToDoArr) // >>  [ undefined, undefined ]

        if (chkToDoArr.length < 1) 
        console.log('no checked toDos or empty list');
    }
}

thanks

1
  • 1
    The only way to return an empty array from .map() is if your input is an empty array. You have to re-think how you approach this, since you cannot embed the logic in the mapping function. Commented Feb 28, 2019 at 21:47

2 Answers 2

1

I believe what you need to use is filter instead of map. For example:

let chkToDoArr = toDoArr.filter(function (obj) {
  return obj.chk === true
})

console.log(chkToDoArr) // >>  []

Filter returns an array of results where the comparing function returns a truthy.

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

2 Comments

thank you, but the return is an array of obj but btw it's working like this console.log (chkToDoArr) // >> [ { chk: true, id: 1, toDo: 'todo' }, { chk: true, id: 2, toDo: 'todo1' } ] --------------------------------------------------------------------------------------- if (chkToDoArr.length < 1) console.log('no checked toDos or empty list'); else { for (let val of chkToDoArr){ console.log( val.toDo ) /*>> todo todo1*/ } }
I think you need to be more explicit with what you are trying to achieve, as I'm not sure.
0
 let chkToDoArr = toDoArr.filter(obj => obj.chk).map(obj => obj.toDo)
  1. filter method checks if received elemet prop is true returns that elemen. on the false returns nothing. if on the array all objects element prop(chk) is false returns empty array
  2. second action is map filtered data and return array with toDo prop

1 Comment

you don't understand what going on here? question was if not exist any (or it is false) obj.chk prop return empty array otherwise return todo prop... that is solution

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.