Reputation: 1734
I have two arrays like arr1, arr2. Each array having different kind of values. In array one i have repeated some values in multiple times. How can i get same value index and value? Also, how to get array two values from array one same value index?
var arr1 = [100, 200, 100, 300, 600, 200];
var arr2 = [1, 2, 3, 4, 5, 6];
For example, If my custom value is 200. arr1 result will be [1, 5]. How to get arr2 value like [2, 6].
Upvotes: 3
Views: 2519
Reputation: 894
One way of doing this is go through the array 1 and once find your custom value
Here is the code
var arr1 = [100, 200, 100, 300, 600, 200];
var arr2 = [1, 2, 3, 4, 5, 6];
var index=[];
var result=[];
var customValue=200;
for(var i=0;i<arr1.length;i++){
if(arr1[i]==customValue){
result.push(arr2[i]);
index.push(i);
}
}
console.log(index);
console.log(result);
Upvotes: 0
Reputation: 692
var arr1 = [100, 200, 100, 300, 600, 200];
var obj={};
for(var iloop=0; iloop< arr1.length; iloop++){
if(obj[ arr1[iloop] ]){
obj[ arr1[iloop] ].push(iloop) ;
}else{
obj[ arr1[iloop] ] = [iloop];
}
}
for(var k in obj){
if(obj[k] && obj[k].length>1){
console.log(k, obj[k])
}
}
Upvotes: 2
Reputation: 386560
I suggest to use Array#filter
with the target array and return true
(later also the value) if the element of array1
with the same index is equal to the search value.
The
filter()
method creates a new array with all elements that pass the test implemented by the provided function.
var arr1 = [100, 200, 100, 300, 600, 200],
arr2 = [1, 2, 3, 4, 5, 6];
function getMappedValues(array1, array2, value) {
return array2.filter(function (_, i) {
return array1[i] === value;
});
}
document.write('<pre>' + JSON.stringify(getMappedValues(arr1, arr2, 200), 0, 4) + '</pre>');
Upvotes: 1
Reputation: 68393
try
function findIndexes(arr, value, fromIndex, indexes)
{
indexes = indexes || [];
var index = arr.indexOf(value, fromIndex+1);
console.log(index);
if ( index != -1)
{
indexes.push(index);
findIndexes(arr, value, index, indexes)
}
}
var arr1 = [100, 200, 100, 300, 600, 200];
var arr2 = [];
var value = 200;
findIndexes(arr1, value, -1, arr2);
document.write(arr2);
Upvotes: 0
Reputation: 29172
Something like this:
var arr1 = [100, 200, 100, 300, 600, 200];
var arr2 = [1, 2, 3, 4, 5, 6];
var _arr1 = [];
var _arr2 = [];
for( var i = arr1.indexOf(200); i >= 0; i = arr1.indexOf(200,i+1) ) {
_arr1.push(i);
_arr2.push( arr2[i] );
}
console.log( _arr1, _arr2 );
Upvotes: 2