I have data which could be simply explained with these three arrays (although in a much larger scale):
var arrayOfVariables = ['var1', 'var2', 'var3', 'var4'];
var arrayWithValues = [20, 10, 30, 40];
var arrayToFilter = ['var1', 'var3'];
Ideally I would want to filter the arrayToFilter and see if it contains any variable from my arrayOfVariables. If they do I want to use their indexes to get an array of correct values from the arrayWithValues. This means var1 = 20, var2 = 10, var3 = 30, var4 = 40. Because arrayToFilter contain var1 och var 3 my last array would be:
var output = [20, 30];
Does anyone know if this is possible in a efficient way, preferably without for-loops or similar. Maybe filter/map/reduce?
* UPDATE *
var arrayOfVariables = ['var3', 'var2', 'var1', 'var4'];
var arrayWithValues = [30, 10, 20, 40];
var arrayToFilter = ['var1', 'var3'];
If I would change the order of the arrays to the above I would still like an output of [20, 30]. This means I want the values sorted after the arrayToFilter: So first var1 (20) and then var3 (30).
Map
with the key/value pairs taken from the first two arrays. - 4castleundefined
for missing items. - Nina Scholzhas
. The point of usingMap
is that it has much faster lookup times than a call toindexOf
orincludes
. It makes the quadratic solution into a linear one. - 4castle