David Zoufalý
David Zoufalý

Reputation: 15

Every iteration starts with previous iteration result

How do you iterate over an array with every iteration taking the previous result? I am looking for same value in array B like is in array A, but array A has only one value, like result of for in loop. I want return array C which is starting array substracted of all items in array A.

I have this code so far:

x = newArray.indexOf(zeme[0]);

for (b = 0; b < newArray.length; b++) {
  if (x === b) {
    newArray.splice(b, zeme.length);
  }
}

With values:

array B = ['can', 'usa', 'eng'];

array A = ['eng'];
array A = ['can'];

Getting results:

array C = ['can', 'usa']
//first iteration, found 'eng' and deleted.
array C = ['usa', 'eng']
//second iteration found 'can' and deleted.

Required result:

array C = ['usa']
//after first iteration in array left only two items ['can', 'usa']
//after second iteration take array ['can', 'usa'] and splice 'can'

Upvotes: 0

Views: 58

Answers (1)

AKX
AKX

Reputation: 169184

If

I want return array C which is starting array substracted of all items in array A.

is the gist of your question, it sounds like you want array intersection.

function intersect(a, b) {
    return a.filter((v) => b.indexOf(v) === -1);
}

console.log(intersect(['can', 'usa', 'eng'], ['usa', 'eng']));

outputs

['can']

(Note: the above implementation is not optimized; it can get terribly slow for large b arrays, as the worst-case complexity is O(n^2) there.)

Upvotes: 3

Related Questions