0

Assuming I have 2 arrays :

let a = [1, 2, 3]
let b = [1, 2, 3, 4, 5]

and I need a to have the difference from b so a = [1, 2, 3, 4, 5]

Is there a cleaner or more performant way than

a.concat(b.filter(x => !a.includes(x))) ?

adaba
  • 374
  • 1
  • 18
  • `Is there a cleaner way than` - by "cleaner" do you mean a way that actually produces the required result? since that code produces `[1,2,3,[4,5]]` - not the result you require – Bravo Nov 02 '19 at 23:31
  • `more performant` - are you dealing with arrays with hundreds of thousands of elements? if not, then *performant* isn't an issue (unless you're running on a steam powered 80286 or something – Bravo Nov 02 '19 at 23:33
  • @Bravo just noticed it, edited – adaba Nov 02 '19 at 23:34
  • 1
    Could use a Set to return the unique values `a= [...new Set( a.concat(b))]` – charlietfl Nov 02 '19 at 23:35
  • If you truly want performance, which I don't think is a big concern nowadays, then steer clear of array functions and use loops. – ibrahim mahrir Nov 02 '19 at 23:35
  • @ibrahimmahrir can you explain why it iterates `b` more than once in my case ?, is it the concat ? – adaba Nov 02 '19 at 23:39

0 Answers0