# JavaScript - Determine all possible ways a group of values can be removed from a sequence

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that determines how many different ways we can remove a group of values from a sequence, leaving the original sequence in order (stable), and making sure to remove only one instance value each from the original sequence.

For example − If the sequence array is −

const arr = [1, 2, 1, 3, 1, 4, 4];

And the array to be removed is −

const arr2 = [1, 4, 4];

Then there are three possible ways of doing this without disrupting the order of elements −

1 --> [2, 1, 3, 1]
2 --> [1, 2, 3, 1]
3 --> [1, 2, 1, 3]

Therefore, our function should output 3 for these sequences. The code for this will be −

## Example

const arr = [1, 2, 1, 3, 1, 4, 4];
const arr2 = [1, 4, 4];
const possibleRemovalCombinations = (original, part) => {
const sorter = (a, b) => a - b;
part.sort(sorter);
let place = [];
part.forEach(el => {
place[el] = []
});
original.forEach((el, index) => {
if(place[el]){
place[el].push(index);
}
});
let connection = part.map(el => place[el].slice());
for(let i = 1; i < connection.length; i++){
if (part[i - 1] != part[i]){
continue;
}
let left = connection[i - 1];
while(connection[i] <= left){
connection[i].shift();
};
};
for (let i = connection.length - 2; i >= 0; i--) {
if(part[i] != part[i + 1]){
continue;
}
let right = connection[i + 1][connection[i + 1].length - 1];
while(connection[i][connection[i].length - 1] >= right){
connection[i].pop();
};
};
const combineArray = (step, prev, combination) => {
for (let i = 0; i < connection[step].length; i++) {
let curr = connection[step][i];
if(prev >= curr && original[prev] == original[curr]){
continue;
}
if(step + 1 == connection.length){
combinations.push(combination.concat([curr]))
}
else {
combineArray(step + 1, curr, combination.concat([curr]));
};
};
};
let combinations = [], res = [];
combineArray(0, -1, []);
for (let i = 0; i < combinations.length; i++) {
let copy = original.slice();
combinations[i].forEach(el => copy[el]);
res[i] = copy.filter(el => el !== undefined);
};
return res.length;
};
console.log(possibleRemovalCombinations(arr, arr2));

## Output

And the output in the console will be −

3