1

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

2 Answers 2

1

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`,
  ));
}

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

2 Comments

but what if I need to find not only index of query inside the big array, but also in this array [ 'kek', 'lol' ] so If it found the index in big array also search in the array that it found (for examle "kek" is at index 0 at smaller array)
I've made an edit, where you can extract in which data index the key is and in which position
0
userInput = 'kek'
  let item = data.map((item, indx) => {
     item.includes(userInput) ? return({"indx":indx,"nestedIndex":item.indexOf(userInput)}) : null
   })

map over the data array and if the nested array had the item your searching for than return the index of the array and the index of the item with in that array

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.