interwebjill
interwebjill

Reputation: 950

Find value and index of Javascript array element when the index meets another condition

I have two arrays:

arr1 = [0,1,1,0]
arr2 = [a,b,c,d]

I would like to find the values and corresponding indices of arr2[ i ] where i is such that arr1[ i ] != 0 without looping through each position in arr2. What efficient techniques could do something like the following:

arr2.forEach( ( 'element with index such that arr1[index] != 0') => {} );

** EDIT ** The initial posting of this question wasn't clear about needing to record the indices of the elements that met the condition.

Upvotes: 0

Views: 2260

Answers (5)

Shidersz
Shidersz

Reputation: 17190

Another solution to this is using reduce() over the arra1:

const arr1 = [0,1,1,0,1];
const arr2 = ["a","b","c","d","e"];

let res = arr1.reduce(
    (acc, v, idx) => v ? acc.concat({val: arr2[idx], idx}) : acc,
    []
);

console.log(res);

Upvotes: 1

Adrian Brand
Adrian Brand

Reputation: 21658

You can reduce array 1 to the indexes you want and when you need the values you can maps them to their value in array 2

let arr1 = [0, 1, 1, 0];
let arr2 = ['a', 'b', 'c', 'd'];

let indexes = arr1.reduce((results, val, index) => {
  if (val) {
    results.push(index);
  }
  return results;
}, []);

console.log(indexes);

let vals = indexes.map(idx => arr2[idx]);

console.log(vals);

Upvotes: 0

Konstantin Dobler
Konstantin Dobler

Reputation: 326

EDIT: getting the indices too is easy - updated the answer

You say you don't want to loop through arr2 but what you could do is loop through arr1 and collect the respective value of arr2 everytime you get a hit like so:

let result = []
arr1.forEach((value, idx) => {
    if (value !== 0) result.push({index: idx, value: arr2[idx]})
}

Though this seems like kind of a hack around your requirements. Other than this I don't think you have another choice but to loop through either array (optimization: only loop through the smallest one).

If you want the complete result you have to check every element of arr2 for the condition because if you don't there could still be some elements missing from your result.

Upvotes: 1

thedude
thedude

Reputation: 9822

Simply use filter:

arr1 = [0,1,1,0]
arr2 = ['a','b','c','d']

console.log( arr2.filter((item, index) => arr1[index] !== 0) )

Upvotes: 0

Twisty
Twisty

Reputation: 30899

Try $.each():

$(function() {
  var arr1 = [0, 1, 1, 0];
  var arr2 = ['a', 'b', 'c', 'd'];

  $.each(arr1, function(k, v) {
    if (!v) {
      console.log(arr2[k]);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Obviously, arrays must be of equal size or arr1 can be smaller than arr2.

Hope that helps.

Upvotes: -1

Related Questions