Ad

Searching For Data In Arrays [Node.JS]

- 1 answer

I have a question: (sorry for the bad formatting)

I have an array:

[
    {
        "data": [
            [
                "kek",
                "lol"
            ],
            [
                "notkek",
                "notlol"
            ]
        ]
    }
]

If someone writes "kek" it should search it in the "data" array and return the "kek" position inside its array (["kek","lol"])

and its array position

{
    "data": [
        [
            "kek",
            "lol"
         ]}

(in this case "data[0]")

If anybody knows the answer, please help me

Ad

Answer

The method Array.findIndex and Array.includes may help you

const obj = {
  data: [
    [
      'kek',
      'lol'
    ],
    [
      'notkek',
      'notlol'
    ],
  ],
};

const keyToSearch = 'kek';

// We look for the key
const index = obj.data.findIndex(x => x.includes(keyToSearch));

if (index === -1) {
  console.log(`We didn't found ${keyToSearch}`);
} else {
  console.log(`We found ${keyToSearch} at index ${index}`);
}


Double index recuperation

const obj = {
  data: [
    [
      'kek',
      'lol'
    ],
    [
      'notkek',
      'notlol'
    ],
    [
      'notkek',
      'notlol',
      'otherstuff',
      'kek',
      'test',
    ],
  ],
};

const keyToSearch = 'kek';

const ret = obj.data.reduce((tmp, x, xi) => {
  // We look for the key
  const index = x.findIndex(y => y === keyToSearch);

  if (index === -1) return tmp;

  return [
    ...tmp,

    {
      absoluteIndex: xi,
      relativeIndex: index,
    },
  ];
}, []);


if (!ret.length) {
  console.log(`We didn't found ${keyToSearch}`);
} else {
  ret.forEach(({
    absoluteIndex,
    relativeIndex,
  }) => console.log(
    `We found ${keyToSearch} at`,
    `data index ${absoluteIndex}, in ${relativeIndex} position`,
  ));
}

Ad
source: stackoverflow.com
Ad