Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 140190

Get an array of N values(that are not present at "exclude" array) from an array X scanning in reverse and mutate the X array removing the added items

$
0
0

I have an array named queue which will have some finite values in it. I want at max 2 records in the result array from the queue"scanning from the last index" where the values that are to be added result should not exist in the exclude array.

In short the conditions are:

  • The queue array needs to be scanned from right to left direction.
  • If the value scanned is not found in the exclude array, the value should be added to the result array.
  • When the result array thus obtained will have the length of maximum size N or when the end of the queue array is reached, the process should be terminated.
  • The queue array should be mutated in this process i.e. after adding the value to the result, the value should removed from the queue array(or can be removed at last it doesn't matter but it should be observed when the process terminates).

For an example:

let queue = [7, 9, 3, 4, 5];
let exclude = [4, 6, 10];
let resultCount = 2; // result's maximum length
let result = []; // will contain the result values

The expected end result looks like this:

result = [5, 3]; // can be in any order
queue = [7, 9, 4]; // mutated queue

Here, scanning from the last index, the value 5 is found unique and added to the result array but value 4 is skipped because it exists on the exclude array. Then the value 3 is found unique and added to the result array. Since the maximum size of the result array, 2 is reached i.e. [5, 3], the process is terminated. The matching values will also be removed from the queue array leaving the array [7, 9, 4] at the end of the process.

Is there any way achieve this behaviour?


Viewing all articles
Browse latest Browse all 140190

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>