lache
lache

Reputation: 830

How to filter a word using array.filter method

I simply want to know how to return the indexes of the objects whose name property is equal to "Bob" using the filter method. (in this case one Index for simplicity)

data.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);

Should show index:14,17

Upvotes: 0

Views: 108

Answers (2)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Using reduce method

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"));

Upvotes: 0

Jamiec
Jamiec

Reputation: 136104

This is as simple as a filter and a map

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

Upvotes: 1

Related Questions