Home > Net >  Subtract Two Arrays With Duplicate Elements
Subtract Two Arrays With Duplicate Elements

Time:11-17

Lets say I have two arrays as follows:

const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']
const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']

I want to subtract array A from array B. With the result looking like this:

const result = ['Mo', 'Mo', 'Sa']

How can this be achieved? It seems so simple but I cannot get it working.

Essentially this should remove everything from B once that is in A.

CodePudding user response:

const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']
const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']

console.log(A.reduce((b, a)=>
  (b.includes(a) && b.splice(b.indexOf(a),1), b), [...B]))

CodePudding user response:

A funny little filter() over a map of A.

const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']
const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']

const aMap = A.reduce((a, c) => (a[c] = (a[c] ?? 0)   1, a), {})
const result = B.filter(n => !(aMap[n]-- > 0))

console.log(result)

CodePudding user response:

const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']
const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']

const C = B.map(el => {
    const elIndexInA = A.findIndex(e => e === el)
    if (elIndexInA === -1) {
        return el
    }
    A.splice(elIndexInA, 1)
}).filter(el => el)

console.log(C)

CodePudding user response:

Try this:

const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']
const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']
let res = B;
A.forEach(val => {
  for(let i = 0; i < res.length; i  ) {
    if(res[i] === val) {
      res.splice(res.indexOf(val), 1);
      break;
    }
  }
});
  • Related