Reputation: 1215
given the following data:
const array = [
{name: one, completed: false},
{name: two, completed: false},
{name: three, completed: false},
{name: four, completed: false},
]
const arrayTwo = [
{name: one, completed: true},
{name: two, completed: true},
{name: three, completed: false},
{name: four, completed: false},
]
I need to be able to return:
//from array
[
{name: one, completed: false}
]
//from arrayTwo
[
{name: one, completed: true},
{name: two, completed: true},
{name: three, completed: false},
]
So to the question: How can I map/filter/reduce these arrays to return all items up to and including the first one with the param meeting condition of:
completed: false
...or the first one if they all meet the condition of:
completed: false
As always any and all direction is greatly appreciated, so thanks in advance!
Upvotes: 0
Views: 39
Reputation: 37745
You can use a simple for loop, keep pushing values to op
and once you found completed
return op
const array = [{name: 'one', completed: false},{name: 'two', completed: false},{name: 'three', completed: false},{name: 'four', completed: false},]
const arrayTwo = [{name: 'one', completed: true},{name: 'two', completed: true},{name: 'three', completed: false},{name: 'four', completed: false},]
const fn = arr => {
let op = []
for(let i=0; i<arr.length; i++){
op.push(arr[i])
if(!arr[i].completed){
return op
}
}
}
console.log(fn(array))
console.log(fn(arrayTwo))
Upvotes: 0
Reputation: 138427
const result = array.slice(0, array.findIndex(it => !it.completed) + 1);
Upvotes: 3