【问题标题】:Filter Array till value match过滤数组直到值匹配
【发布时间】:2021-08-22 07:25:06
【问题描述】:

我喜欢从数组的开头获取记录,直到此示例中第一个字符串“red”匹配(4 个第一条记录)

const arrayFull = [
{id:'1' type:'blue'},
{id:'2' type:'blue'},
{id:'3' type:'blue'},
{id:'4' type:'blue'},
{id:'5' type:'red'},
{id:'6' type:'blue'},
{id:'7' type:'blue'},
{id:'8' type:'blue'},
{id:'9' type:'red'},
{id:'10' type:'red'},
];

示例输出需要它:

[ 
{id:'1' type:'blue'},
{id:'2' type:'blue'},
{id:'3' type:'blue'},
{id:'4' type:'blue'}
]

【问题讨论】:

    标签: arrays ecmascript-6 filter


    【解决方案1】:

    以声明方式:

    arrayFull.slice(0, arrayFull.findIndex((e) => e.type === "red"));
    

    首先找到type: 'red' 第一次出现的索引,然后将数组的副本切分到该点。

    这只有在至少出现一次type: 'red' 时才能正常工作,因为否则findIndex 会返回-1。要使其在所有情况下都能正常工作,您可以检查索引是否为 -1,如果为 true,则返回原始数组的副本。

    再次声明:

    const arrayFull = [{id:"1",type:"blue"},{id:"2",type:"blue"},{id:"3",type:"blue"},{id:"4",type:"blue"},{id:"5",type:"red"},{id:"6",type:"blue"},{id:"7",type:"blue"},{id:"8",type:"blue"},{id:"9",type:"red"},{id:"10",type:"red"}];
    
    // The solution:
    
    const firstRedIndex = arrayFull.findIndex((e) => e.type === "red");
    const result = firstRedIndex === -1 ? [...arrayFull] : arrayFull.slice(0, firstRedIndex);
    console.log(result);

    【讨论】:

      【解决方案2】:

      只需运行传统的for 循环即可。遍历项目,一旦你发现red 跳出循环

      const arrayFull = [
        { id: "1", type: "blue" },
        { id: "2", type: "blue" },
        { id: "3", type: "blue" },
        { id: "4", type: "blue" },
        { id: "5", type: "red" },
        { id: "6", type: "blue" },
        { id: "7", type: "blue" },
        { id: "8", type: "blue" },
        { id: "9", type: "red" },
        { id: "10", type: "red" }
      ];
      const result = [];
      for (let i = 0; i < arrayFull.length; i++) {
        if (arrayFull[i].type === "red") {
         break;
        } else {
         result.push(arrayFull[i]);
        }
      }
      console.log(result);

      【讨论】:

        猜你喜欢
        • 2016-05-28
        • 1970-01-01
        • 2016-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-11
        相关资源
        最近更新 更多