-1

In Javascript, I have this

var a = ["1","2","3"]
var b = ["3","4","5"]

assuming "b" reads "a" and removes the 3 because it is repeated, how can I get this?

var c = ["4","5"]

Thank You!

Alizee Ticona
  • 61
  • 1
  • 9
  • [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) and [`includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) – kelsny Oct 12 '22 at 03:18

2 Answers2

1

Check if value exists on another array using includes()

Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

You can remove values by using filter()

Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

To do what you want:

const a = ["1","2","3"]
const b = ["3","4","5"]
const c = b.filter((value) => !a.includes(value))

This has been answered before and is in detail: How to get the difference between two arrays in JavaScript?

captainskippah
  • 1,350
  • 8
  • 16
  • 1
    If the question is a dupe, you shouldn't be answering it, just voting to close (thank you for doing that). Note that your answer is wrong anyway... – Nick Oct 12 '22 at 03:23
  • 1
    Thank You, but this returns ['3'], and not ["4","5"] – Alizee Ticona Oct 12 '22 at 03:23
1
  • You can use set and spread operators.
  • set has property to have all unique value object.
  • Below we are using Set constructor passing values using spread operator and it return an object so to get an array we are again passing that object with spread operator.

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

let c = [...new Set([...a, ...b])];

console.log(c);
Nexo
  • 2,125
  • 2
  • 10
  • 20