0

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.