【问题标题】:How to filter a word using array.filter method如何使用 array.filter 方法过滤单词
【发布时间】:2021-05-05 15:38:38
【问题描述】:

我只是想知道如何使用过滤器方法返回 name 属性等于“Bob”的对象的索引。 (在这种情况下,为简单起见一个索引)

数据.json

[
 {
    "index": "14",
    "name": "Bob",
    "age": "23",
  },
  {
    "index": "23",
    "name": "John",
    "age": "30",
  },
  {
    "index": "17",
    "name": "Bob",
    "age": "25",
  },
]

app.js

const data = require("./data.json");


const searchword = "Bob";
const result = data.filter((word) => ???word === searchword???);
console.log(result);

应该显示索引:14,17

【问题讨论】:

    标签: javascript arrays filter properties


    【解决方案1】:

    这就像filtermap 一样简单

    const data = [
     {
        "index": "14",
        "name": "Bob",
        "age": "23",
      },
      {
        "index": "23",
        "name": "John",
        "age": "30",
      },
      {
        "index": "17",
        "name": "Bob",
        "age": "25",
      },
    ]
    
    const searchWord = "Bob";
    const result = data.filter(x => x.name == searchWord) // find by searchWord
                       .map(x => x.index); // get the index
    console.log(result.join(",")); // result is an array

    【讨论】:

      【解决方案2】:

      使用reduce方法

      const data = [
        {
          index: "14",
          name: "Bob",
          age: "23",
        },
        {
          index: "23",
          name: "John",
          age: "30",
        },
        {
          index: "17",
          name: "Bob",
          age: "25",
        },
      ];
      
      const getIndexes = (arr, word) =>
        arr.reduce(
          (acc, { index, name }) => (name === word ? acc.concat(index) : acc),
          []
        ).toString();
      
      console.log(getIndexes(data, "Bob"));

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-28
        • 1970-01-01
        • 2020-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多