使用Javascript删除公共元素并将新数组从一个数组添加到另一个数组

时间:2018-03-23 09:39:57

标签: javascript

输入中有两个数组,

var array1 = [1,2,3,4,5,6];

var array2 = [3,4,6,8];

输出应为:

var finalArray = [1,2,5,8];

请使用javascript向我推荐一个解决方案。 我想迭代array1。

4 个答案:

答案 0 :(得分:2)

您可以使用array.prototype.filter和array.prototype.concat:

var arr1 = [1,2,3,4,5,6];
var arr2 = [3,4,6,8];

var res = [].concat(
  arr1.filter(e => !arr2.includes(e)),
  arr2.filter(e => !arr1.includes(e))
);

console.log(res);

甚至更短的ES6 spread

var arr1 = [1,2,3,4,5,6];
var arr2 = [3,4,6,8];

var res = [...arr1.filter(e => !arr2.includes(e)), ...arr2.filter(e => !arr1.includes(e))];

console.log(res);

答案 1 :(得分:1)

使用filterconcat

var output = array1.filter( s => !array2.includes(s) ) 
             .concat( 
                array2.filter( s => !array1.includes(s) ) )

<强>演示

&#13;
&#13;
var array1 = [1, 2, 3, 4, 5, 6];

var array2 = [3, 4, 6, 8];

var output = array1.filter(s => !array2.includes(s)).concat(array2.filter(s => !array1.includes(s)));

console.log(output);
&#13;
&#13;
&#13;

<强>解释

1)首先,filter array1array2的值filter array2

2)其次,array1 concat中的值add-test-source <project> ... <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>3.0.0</version> <executions> <execution> <id>add-test-source</id> <phase>generate-test-sources</phase> <goals> <goal>add-test-source</goal> </goals> <configuration> <sources> <source>some directory</source> ... </sources> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>

3) <sources> <source>some directory</source> ... </sources> 1)和2)

答案 2 :(得分:1)

您可以使用.filter()过滤数组以包含任何元素,这些元素也包含在另一个数组中,然后使用.concat()组合它们:

&#13;
&#13;
var array1 = [1, 2, 3, 4, 5, 6];

var array2 = [3, 4, 6, 8];

var arr1 = array1.filter(e => !array2.find(f => f == e));
var arr2 = array2.filter(e => !array1.find(f => f == e));
var arr = arr1.concat(arr2);
console.log(arr);
&#13;
&#13;
&#13;

答案 3 :(得分:1)

您可以尝试使用数组SELECT COUNT( DISTINCT col1 ) ... filter()

&#13;
&#13;
concat()
&#13;
&#13;
&#13;