我有两个JavaScript数组:
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
Run Code Online (Sandbox Code Playgroud)
我希望输出为:
var array3 = ["Vijendra","Singh","Shakya"];
Run Code Online (Sandbox Code Playgroud)
输出数组应该删除重复的单词.
如何在JavaScript中合并两个数组,以便我只按照它们插入原始数组的相同顺序从每个数组中获取唯一项?
有没有办法在JavaScript中返回两个数组之间的差异?
例如:
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
// need ["c", "d"]
Run Code Online (Sandbox Code Playgroud)
任何建议都非常感谢.
我试图找出一种有效的方法来从数组中删除重复的对象,并寻找最有效的答案.我环顾互联网,一切似乎都在使用原始数据...或者不能扩展到大型数组.这是我目前的实现,可以改进,并希望尝试避免标签.
Test.prototype.unique = function (arr, artist, title, cb) {
console.log(arr.length);
var n, y, x, i, r;
r = [];
o: for (i = 0, n = arr.length; i < n; i++) {
for (x = 0, y = r.length; x < y; x++) {
if (r[x].artist == arr[i].artist && r[x].title == arr[i].title) {
continue o;
}
}
r.push(arr[i]);
}
cb(r);
};
Run Code Online (Sandbox Code Playgroud)
并且数组看起来像这样:
[{title: sky, artist: jon}, {title: rain, artist: Paul}, ....]
Run Code Online (Sandbox Code Playgroud)
订单无关紧要,但如果排序使其更有效率,那么我就迎接挑战......
并且对于那些不知道o的人来说是一个标签,它只是说跳回循环而不是推送到新阵列.
纯javascript请没有库.
回答如此:
以下答案的性能测试:http: //jsperf.com/remove-duplicates-for-loops
jsfiddle链接:http://jsfiddle.net/vN6fn/1/
假设我有这两个对象:
var obj1 = { data: [
{id:1, comment:"comment1"},
{id:2, comment:"comment2"},
{id:3, comment:"comment3"}
] }
var obj2 = { data: [
{id:2, comment:"comment2"},
{id:3, comment:"comment3"},
{id:4, comment:"comment4"}
] }
Run Code Online (Sandbox Code Playgroud)
最终对象应如下所示:
var final = { data: [
{id:1, comment:"comment1"},
{id:2, comment:"comment2"},
{id:3, comment:"comment3"},
{id:4, comment:"comment4"}
] }
Run Code Online (Sandbox Code Playgroud)
这里有一些要考虑的事情:
$.extend()替换对象,$.merge()不删除重复(我知道我可以做循环,但我正在寻找一个更好的方法来做到这一点).
我有一个用空格分隔的.txt文件,其中包含重复项。我想删除骗子,但并不容易。
该文件包含: orange orange apple apple pear
起初,我在txt扩展名方面遇到错误。我更新了主包含
const fs = require('fs');
require.extensions['.txt'] = function (module, filename) {
module.exports = fs.readFileSync(filename, 'utf8');
Run Code Online (Sandbox Code Playgroud)
这有助于解决错误,之后我就可以创建一个const。
const fruitList = require('../support/fruitList.txt');
Run Code Online (Sandbox Code Playgroud)
但是,我仍然无法删除重复项。我尝试了neek,那也不起作用。
javascript ×5
arrays ×3
algorithm ×1
ecmascript-6 ×1
jquery ×1
json ×1
merge ×1
node.js ×1
sorting ×1