Ad
Searching For Data In Arrays [Node.JS]
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
Related Questions
- → How do I create an array from a single form input box with php on octobercms?
- → Print the output value of an array in twig [OctoberCMS]
- → Declare an array variable to the controller/component [Laravel, October CMS]
- → Removing a JavaScript property inside a specific Object within an Array
- → Javascript loop indexing issue
- → search array without duplicates React.js
- → Populating array with items from different HTML attributes
- → Get all index value of 1 from binary "01000111"
- → Remove objects from array - Two different approaches, two different results when consulting the length of each array
- → Compare values in two arrays
- → adding multiple polygons in google maps using loops and arrays
- → .split() JS not "splitting" correctly?
- → Vue.js - Binding radio elements of same name to array
Ad