Reputation: 480
How to splice
the string value so the output only become 'LA1','LA4'
. I tried the method below but it still gave me string_2
output.
var string_1 = 'LA2,LA3'
var string_2 = "LA1,LA2,LA3,LA4";
var unique_1 = string_1.split(',');
var unique_2 = string_2.split(',');
const index = unique_2.indexOf(unique_1);
if (index > -1) {
unique_2.splice(index, 1);
}
console.log(unique_2);
Upvotes: 0
Views: 70
Reputation: 92440
Instead of using splice()
You can filter()
with includes()
.
var string_1 = 'LA2,LA3'
var string_2 = "LA1,LA2,LA3,LA4";
var unique_1 = string_1.split(',');
var unique_2 = string_2.split(',');
var filtered = unique_2.filter(s => !unique_1.includes(s))
console.log(filtered);
If your lists are very large, you might want to use something other than an array with includes()
such as a Set
that offers constant time lookups.
Upvotes: 1
Reputation: 2761
using reduce:
var string_1 = 'LA2,LA3'
var string_2 = "LA1,LA2,LA3,LA4";
var unique_1 = string_1.split(',');
var unique_2 = string_2.split(',');
const result = unique_2.reduce((acc, item) => {
!string_1.includes(item) && acc.push(item)
return acc
}, [])
console.log(result)
Upvotes: 0
Reputation: 2142
Array.prototype.indexOf() only finds one element and can not find an array. To get the expected value, you can do as follows.
var string_1 = 'LA2,LA3'
var string_2 = "LA1,LA2,LA3,LA4";
var unique_1 = string_1.split(',');
var unique_2 = string_2.split(',');
unique_2 = unique_2.filter(item => !unique_1.includes(item));
console.log(unique_2);
Upvotes: 0