how to get an array with unique values from two arrays code example
Example 1: return unique values array from two arrays java
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class MergeNames {
public static String[] uniqueNames(String[] names1, String[] names2) {
String[] combine = Stream.concat(Arrays.stream(names1), Arrays.stream(names2))
.toArray(String[]::new);
List<String> distinctElements = Arrays.stream(combine)
.distinct()
.collect(Collectors.toList());
return distinctElements.toArray(new String[distinctElements.size()]);
}
public static void main(String[] args) {
String[] names1 = new String[] {"Ava", "Emma", "Olivia"};
String[] names2 = new String[] {"Olivia", "Sophia", "Emma"};
System.out.println(String.join(", ", MergeNames.uniqueNames(names1, names2))); // should print Ava, Emma, Olivia, Sophia
}
}
Example 2: find unique values between multiple array
var array3 = array1.filter(function(obj) { return array2.indexOf(obj) == -1; });
Example 3: return uncommon from two arrays js
let array = [1,2,3,4,5,6,78,9];
function except(array,excluded){
let newArr,temp,temp1;
check1=array.filter(function(value)
{
return excluded.indexOf(value) == -1;
});
check2=excluded.filter(function(value)
{
return array.indexOf(value) == -1;
});
output=check1.concat(check2);
return output;
}
except(array,[1,2])
//so the output would be => [ 3, 4, 5, 6, 78, 9 ]