-2

Subtraction of two arrays. a=["AT","IN","UK","US"] and b=["UK","ZA"]. I need result like a-b = ['"AT","IN","US"]

I am trying to subtract two arrays in above way, but instead of getting the correct answer I am ending up with a[] always. Below is my code:

var prevCountries = ["AT","IN","UK","US"]; 
var sectedCountries= ["UK","ZA"] ;
var deletedCountries =[];
deletedCountries =prevCountries ;

console.log(deletedCountries);
for(i=0;i<prevCountries.length;i++)
{
    for(j=0;j<=selectedCountries.length;j++)
    {
    if (prevCountries.includes(selectedCountries[j]))   
        {
            var index = deletedCountries.indexOf(sectedCountries[j]);
            if (index > -1) {
                deletedCountries.splice(index, 1);
            }
        }
    }
}
Stefan Becker
  • 5,695
  • 9
  • 20
  • 30
Ravi
  • 49
  • 8

2 Answers2

-1

Using filter() you can remove the element of b array from array a.

Make an iteration over array a using filter(). In every cycle of the iteration check if the element of a is not exist in array b. filter() keep the element if the callback returns true otherwise it remove the current cycle element.

const a = ['AT','IN','UK','US'];
const b = ['UK','ZA'];
const r = a.filter(i => b.indexOf(i) === -1)
console.log(r)
MH2K9
  • 11,951
  • 7
  • 32
  • 49
  • Thanks clean and simple. works like a charm. One question though why is everyone using const instead of var (I am new to programming). – Ravi Aug 06 '19 at 04:59
  • [Constants are block-scoped, much like variables defined using the let statement. The value of a constant can't be changed through reassignment, and it can't be redeclared.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) – MH2K9 Aug 06 '19 at 05:07
-1

The trivial solution:

prevCountries.filter(x => !sectedCountries.includes(x))

or probably a bit faster one, since sets have much more efficient membership test:

let sectedSet = new Set(sectedCountries)
prevCountries.filter(x => !sectedSet.has(x))
Amadan
  • 191,408
  • 23
  • 240
  • 301