Reputation: 45
I have two arrays:
a = [2,2,3,0,6]
b = [6,3,2,2,0]
I am trying use for loop to match values and get the index of a in a new array c. How can we do this? Notice that there are multiple values which match and so I think the previous match must be skipped.
Upvotes: 0
Views: 73
Reputation: 386550
This is a proposal which respects the last index and looks further.
How it works:
It uses
Array#map
for iterating arrayb
with a callback. map gets an ownthis
space with an really empty objectObject.create(null)
.The callback has on parameter
bb
which is one element of `b.Next is to find the element is in array
a
with aArray#indexOf
and afromIndex
, based on the former searches. The former index is stored in thethis
object, as long as the result is not-1
, because this would reset thefromIndex
to zero.If there is no
this[bb]
or a falsy value ofthis[bb]
take zero asfromIndex
.Later, a found
index
is incremented and stored inthis[bb]
.At least, the index is returned.
var a = [2, 2, 3, 0, 6],
b = [6, 3, 2, 2, 0],
c = b.map(function (bb) {
var index = a.indexOf(bb, this[bb] || 0);
if (index !== -1) {
this[bb] = index + 1;
}
return index;
}, Object.create(null));
console.log(c);
Another solution could be first generate an object with all indices of a
and use it in the iteration of b
for returning the indices.
The example is a bit extended, to show what happen if there is no more than two indices (2) and one without being in a
(7).
The content of aObj with all indices of
a
:{ "0": [3], "2": [0, 1], "3": [2], "6": [4] }
var a = [2, 2, 3, 0, 6],
b = [6, 3, 2, 2, 0, 7, 2],
aObj = Object.create(null),
c;
a.forEach(function (aa, i) {
aObj[aa] = aObj[aa] || [];
aObj[aa].push(i);
});
c = b.map(function (bb) {
return aObj[bb] && aObj[bb].length ? aObj[bb].shift() : -1;
});
console.log(c);
Upvotes: 1
Reputation: 12085
try something like this
var a = [2,2,3,0,6];
var b = [6,3,2,2,0];
var arrayLength_a = a.length;
var arrayLength_b = b.length;
var new_array=[];
for (var i = 0; i < arrayLength_a; i++)
{
for (var j = 0; j < arrayLength_b; j++)
{
if (a[i] == b[j])
{
if(new_array.indexOf(a[i]) === -1)
{
new_array.push(a[i]);
}
}
}
}
Upvotes: 0
Reputation: 2944
As far I Understand, You can try this:
var a = [2,2,3,0,6];
var b = [6,3,2,2,0];
var c = new Array();
for(i = 0; i < b.length; i++)
{
for(j = 0; j < a.length; j++)
{
if(b[i] === a[j] && c.indexOf(j) < 0)
{
c.push(j);
break;
}
}
}
console.log(c); // [4, 2, 0, 1, 3]
Upvotes: 0
Reputation: 4584
loop .map
function and check same value by indexOf
indexOf will return a number,representing the position where the specified search value occurs for the first time, or -1 if it never occurs
var arr = [];
a.map(function(v){
if(b.indexOf(v) > -1){
arr.push(v);
}
});
console.log(arr);
Upvotes: 0
Reputation: 413
If I understand correct.
let c = a.map(i => b.indexOf(i))
or
var c = a.map(function(i) { return b.indexOf(i); });
Upvotes: 0