Modelesq Modelesq - 6 months ago 8
Javascript Question

Check if string value is present within array and return found array value(s) js

I have key identifiers that look like this...

const category = key; // could be "bus","car","plane"


for this example lets go with
"bus"
. I also have an array of strings that look like this...

let transportationFields = [
'bus_station', 'bus_stop', 'bus_line', 'took_bus'
'car', 'buyer_of_car', 'car_model',
'train_number', 'train_trip_num', 'train_stop',
];


Right now I'm grabbing the index of

const transFieldValues = transportationFields.indexOf(category) > -1;


But that just returns
true
. How can I also grab the field it matched to? For example. Since
category = bus
. How can I return all the values it threw true to? (
'bus_station', 'bus_stop', 'bus_line', 'took_bus'
) ?

Thank you for your help in advance!

Answer

You can use .filter() for finding all matches and return them in an array:

let transportationFields = [
  'bus_station', 'bus_stop', 'bus_line', 'took_bus',
  'car', 'buyer_of_car', 'car_model',
  'train_number', 'train_trip_num', 'train_stop',
];

let category = 'bus';

let transFieldValues = transportationFields.filter(function (item) {
  return item.indexOf(category) > -1;
});

document.write (JSON.stringify(transFieldValues));

Or with ES6 arrow function:

let transportationFields = [
  'bus_station', 'bus_stop', 'bus_line', 'took_bus',
  'car', 'buyer_of_car', 'car_model',
  'train_number', 'train_trip_num', 'train_stop',
];

let category = 'bus';

let transFieldValues = transportationFields.filter(w => w.indexOf(category) > -1);

document.write (JSON.stringify(transFieldValues));

Comments