0

I'm just trying to search through a two dimensional array of strings.

The results in found are correct, but the row isn't pushed (correctly) into the array.

The browser shows me this:

enter image description here

function filterItems(arr, query) {
  return arr.filter(function(el) {
    return el.toLowerCase().includes(query.toLowerCase());
  });
}

function FilterArray(unfiltered_array, searchphrase) {
  var filtered_array = [];
  for (var i = 0; i < unfiltered_array.length; i++) {
    var row = unfiltered_array[i];
    var found = filterItems(row, searchphrase);

    if (found.length) {
      console.log(row);
      filtered_array.push(row);
    }
  }


  return filtered_array;

}

const filtered = FilterArray([
  ["LC53005", "bob", "lc56778"],
  ["FP53001", "john", "dog"]
], "lc5");

console.log({
  filtered
});

and I was searching for LC53005.

Any ideas?

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
confusedandtired
  • 139
  • 1
  • 12
  • 3
    What is the expected output? Can you turn this code into a runnable snippet, with the actual call of the function? (Use toolbar to insert snippet). BTW, the code your provided does not output the second half of your image. Also, don't provide images of what is essentially text. Provide the output in JavaScript syntax. – trincot Apr 28 '22 at 12:39
  • Instead of `filtered_array.push(row);` what happens if you would try: `filtered_array.push(found[0]);` – jsN00b Apr 28 '22 at 12:42
  • 1
    The array had seven elements in it when it was logged and returned. Later, code not shown removed those seven elements, so when you expanded it in the console, it didn't have any elements in it before. This is confusing (but useful) behavior of the browser console described in [the linked questions answers](https://stackoverflow.com/questions/38660832/console-log-of-element-children-shows-0-length-but-has-three-entries-when-expand) – T.J. Crowder Apr 28 '22 at 12:43
  • @jsN00b Or `filtered_array.push(found)`. There could be more than one match per row – Ruan Mendes Apr 28 '22 at 12:43
  • 1
    I've made your code snippet be runnable. Please try doing that when you ask questions at StackOverflow. – Ruan Mendes Apr 28 '22 at 13:20

1 Answers1

0

Clearer approach with the expected result !

var unfiltered_array = [
  ["LC53005", "bob", "cat"],
  ["FP53001", "john", "dog"]
];

function filterItems(arr, query) {

  return arr.filter(function(el) {
    return (el.toLowerCase().includes(query.toLowerCase()));
  })
}

function FilterArrayMap(unfiltered_array, searchphrase) {
  return unfiltered_array.map(k => {
    return filterItems(k, searchphrase);
  }).flat();
}

console.log(FilterArrayMap(unfiltered_array, "LC53005"));
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
Tushar Wasson
  • 494
  • 5
  • 10
  • 1
    Here's an even simpler approach if the OP is just trying to find matches... `unfiltered_array.flat().filter((el) => el.toLowerCase().includes(query.toLowerCase));` – Ruan Mendes Apr 28 '22 at 14:16