0

I am trying to filter some data from an array in a JSON file, based on an input of the form string1, string1,string2, string1,string2,string3 etc., that is, some strings separated by a ,.

What I'm trying to do:

let arrInput = document.getElementById('inputBox').val.split(',');

for(let i = 0; i < arrToFilter.length; i++){
    if(.........what to write here?...........){
        arrOutput.push(arrToFilter[i]);
    }
}

return arrOutput;

If the arrInput had a fixed length, I could accomplish this using indexOf != -1 for each element in arrInput, but here, since the length of arrInput is variable, how can I check if at least one of the strings present in arrInput is also present as a substring in arrToFIlter[i]?

Edit:

Example:

Let arrToFilter be ["abcqwer", "pizza", "definition", "abcdef", "example"]

Case 1 :

Say the input entered (in an <input> element) is abc,def.

For this, the arrOutput should be ["abcqwer", "definition", "abcdef"]

Case 2:

Say the input entered is abc

Expected output : ["abcqwer", "abcdef"]

Eagle
  • 318
  • 4
  • 16

2 Answers2

1

Simple way is using some and filter,

var string = 'ad,kk,sb';
var array = ['adik', 'klop', 'pp'];

var stringers = string.split(',');
var result = array.filter((arr) => {
    var isPresent = stringers.some(stringer => arr.includes(stringer));
    return isPresent ? true : false;
});

console.log(result);
Prince Devadoss
  • 416
  • 3
  • 6
1

You need to iterate both arrays

let arrToFilter = ['abcqwer', 'pizza', 'definition', 'abcdef', 'example'];
let arrOutput = [];
let arrInput = document.getElementById('inputBox').value.split(',');

arrToFilter.forEach(filter => {
  arrInput.forEach(input => {
    if (!!input && filter.includes(input)) {
      arrOutput.push(filter);
    }
  });
});
//                      distinct the output
return arrOutput.filter((v, i, a) => i === a.indexOf(v));
Wilhelmina Lohan
  • 2,803
  • 2
  • 29
  • 58