Array search in a JavaScript object

There is an array of objects that has another array to search for. The data structure looks like this:

[
    {
        topic: "First",
        pages: [
            "Alpha",
            "Beta",
            "Gamma",
            "Delta"
        ],
        id: ["1", "2", "3", "4"]
    },
    {
        topic: "Second",
        pages: [
            "Epsilon",
            "Zeta",
            "Eta",
            "Theta"
        ]
        id: ["5", "6", "7", "8"]
    }
]

You need to search for the specified value in the pages arrays, and if the element is found successfully, return its id from the next array. Each id corresponds by index to an element from the first array ("Alpha"-"1", "Epsilon"-"5"). Is there any JS library for such a search? I tried Fuse.js, but it returns the object itself from the array after the search, but I need the returned element to be a string from the array pages (or its id), and not the entire object. Any string is input, for example 'Zeta'. The search should be performed on all rows of the pages arrays, and it should return the indexes of all matches from these arrays, in the case from the example - '6'.

Author: anDev, 2020-01-23

3 answers

You can do this, for example:

const data = [{
    topic: "First",
    pages: [
      "Alpha",
      "Beta",
      "Gamma",
      "Delta"
    ],
    id: ["1", "2", "3", "4"]
  },
  {
    topic: "Second",
    pages: [
      "Epsilon",
      "Zeta",
      "Eta",
      "Theta"
    ],
    id: ["5", "6", "7", "8"]
  },
  {
    topic: "Third",
    pages: [
      "Iota",
      "Kappa",
      "Lambda",
      "Zeta",
      "Zeta"
    ],
    id: ["9", "10", "11", "12", "13"]
  }
];

let query = 'Zeta';
let result = data.reduce((acc, item) => {
  let pageIds = item.pages.reduce((ids, page, ind, arr) => {
    if (page == query) { // или page.includes(query), если нужен поиск по подстроке)
      ids.push(item.id[ind])
    }
    return ids;
  }, [])
  return acc.concat(pageIds);
}, []).join(',');
console.log(result);
 0
Author: Yaant, 2020-01-23 14:01:50

I do not understand why for the sake of this to drag the library, here is an example of a solution:

const myTopics = [
  {
    topic: "First",
    pages: ["Alpha", "Beta", "Gamma", "Delta"],
    id: ["1", "2", "3", "4"]
  },
  {
    topic: "Second",
    pages: ["Epsilon", "Beta", "Eta", "Theta"],
    id: ["5", "6", "7", "8"]
  }
];

function innerArraySearch(topicsArray, pageToSearch) {
  let answer = []; // ответ по умолчанию
  topicsArray.map(topic => {
    // проходим по верхнему массиву
    const indexOfPage = topic.pages.indexOf(pageToSearch); // записываем индекс (не)найденного элемента массива pages
    if (indexOfPage !== -1) {
      answer.push(topic.id[indexOfPage]); // записываем в переменную answer значение topic.id по индексу indexOfPage
    }
  });
  return answer; // возврат по умолчанию
}

console.log(innerArraySearch(myTopics, "Beta"));
 1
Author: Dima, 2020-01-23 13:57:53

var arrOfObj = [
    {
        topic: "First",
        pages: ["Alpha", "Beta", "Gamma", "Delta"],
        id: ["1", "2", "3", "4"]
    },
    {
        topic: "Second",
        pages: ["Epsilon", "Zeta", "Eta", "Theta"],
        id: ["5", "6", "7", "8"]
    }
],
findPageIndex = function(arr, pageName) {
  var res = [];
  for(var i = 0; i < arr.length; i++) {
    var idx = arr[i].pages.indexOf(pageName);
    if(idx != -1){
      res.push({
        topic: arr[i].topic,
        idx: idx,
        id: arr[i].id[idx]
      });
    }
  }
  return res.length > 0 ? res : -1;
}

console.log(findPageIndex(arrOfObj, "Zeta"));
 1
Author: XelaNimed, 2020-01-23 14:03:42