es6数组返回所有达到特定条件的项目,如果所有项目都满足条件,则返回第一个项目

时间:2019-04-11 16:48:18

标签: javascript ecmascript-6

提供了以下数据:

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},
]

我需要能够退货:

//from array
[
  {name: one, completed: false}
]

//from arrayTwo
[
  {name: one, completed: true},
  {name: two, completed: true},
  {name: three, completed: false},
]

关于这个问题: 如何映射/过滤/减少这些数组以返回直到并包括第一个满足参数满足条件的第一个项目:

completed: false

...或第一个(如果它们都满足以下条件):

completed: false

一如既往地非常感谢任何方向,所以在此先感谢!

2 个答案:

答案 0 :(得分:3)

  const result = array.slice(0, array.findIndex(it => !it.completed) + 1);

答案 1 :(得分:0)

您可以使用简单的for循环,将值继续推入op,一旦发现completed,则返回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))