Find the indexOf between two array in JavaScript with a forEach

2

I would like to know how to find the indexOf in JS between two array , a array contains the given values and the other array the values that I want to know your indexOf

var act = [10002197,10001755,10001087,10001879,3508477478,10001881];
var actselect = [10002197,10001755,10001087,10001881];
var posicion = act.indexOf(actselect); //en vez de un numero necesito insertar un array que lo haga por cada valor
console.log(posicion); //la respuesta debería se (0,1,5)
    
asked by Rafael Pereira 14.01.2018 в 20:39
source

2 answers

1

You already got an answer with map , and since your question says forEach , I'll give an example of what it would be like with forEach , taking an additional validation to know if the element exists or not because it would not be filling the array with -1 which is the return value of indexOf when the element does not exist.

var act = [10002197,10001755,10001087,10001879,3508477478,10001881];
var actselect = [10002197,10001755,10001087,10001881];
var posiciones = []; // array posiciones
actselect.forEach(function(el){
	// Sí el indexOf retorna diferente a -1 es porque lo encontró y 
	// lo aañade al array de posiciones
	if((index = act.indexOf(el)) !==-1) 
		posiciones.push(index);
});

console.log(posiciones);

Edit

If you want to obtain the elements from a given array you can use map or filter to return the array depending on the indices specified in actselect

var act = [10002197,10001755,10001087,10001879,10001881]; 
var actselect = [0,1,3]; 
var posicion = actselect.map(function(el){
	return act[el];
});
console.log(posicion);
    
answered by 14.01.2018 / 21:14
source
1

You can use the map method of the Array object that allows you to treat the elements of an array one by one and returns an array with the results:

var act = [10002197,10001755,10001087,10001879,3508477478,10001881];
var actselect = [10002197,10001755,10001087,10001881];

var posiciones = actselect.map((e) => act.indexOf(e)); 

console.log(posiciones);
    
answered by 14.01.2018 в 20:44