0

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.

6
  • 3
    One way or another you're going to have to iterate through the array to find the non-zero entries. Commented Jan 30, 2019 at 22:32
  • The most efficient way would be simple for-loop over arr1... for(...) if (arr1[i] === 0) doSomething(arr2[i]) Commented Jan 30, 2019 at 22:35
  • If collection you iterate over is (relatively) unchanging, then you can sort on a condition, followed by doing binary search for what you are looking for. Commented Jan 30, 2019 at 22:36
  • @Tony sorting is O(n log n) followed by a binary search of O(log n), whereas a loop is O(n). I'm not saying your suggestion is wrong, just that it would require very specific circumstances for that to be the most efficient. Commented Jan 30, 2019 at 22:39
  • I do not know what the actual set interwebjill will be using, nor how it changes during the application s life. That's why I mentioned if it is unchanging. Log n solution might be the most optimal solution, don't Know not enough information Commented Jan 30, 2019 at 22:51

5 Answers 5

1

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

Simply use filter:

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

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

2 Comments

You beat me to it. Also, you could just use arr2.filter((c,i) => !!arr1[i]);
I'd like to capture the index as well as the item. Looking back at my question, I wasn't clear about that.
0

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);

Comments

-1

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.

2 Comments

why an exemple with jQuery ? Array.forEach is ES5 compliant no ?
Fully supported: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - was just another way to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.