合并两个数组,存储唯一元素,并在jQuery中排序 [英] Merging of two arrays, store unique elements, and sorting in jQuery

查看:129
本文介绍了合并两个数组,存储唯一元素,并在jQuery中排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var Arr1 = [1,3,4,5,6];

var Arr2 = [4,5,6,8,9,10];

我正在尝试合并这两个数组,输出为[1,3,4,5,6,4,5,6]

I am trying to do merge these two arrays and output coming is [1,3,4,5,6,4,5,6]

我已经使用$.merge(Arr1, Arr2);这一部分来合并它们.使用警报,我可以看到上面的合并数组.

I have used $.merge(Arr1, Arr2); this piece to merge them. Using alert I can see the merged array like above.

现在我的问题是如何获得以下输出: [1,3,4,5,6,8,9,10]

Now my question is how can I get the following output: [1,3,4,5,6,8,9,10]

即元素应该是唯一的,并且应该按照我提到的相同方式进行排序.

i.e. the elements should be unique as well as sorted in the same manner I have mentioned.

请帮助.

推荐答案

您可以使用 Array.prototype.filter() 仅返回唯一元素.

You can use Array.prototype.sort() to do a real numeric sort and use Array.prototype.filter() to only return the unique elements.

您可以将其包装到类似于以下内容的帮助器中:

You can wrap it into a helper similar to this:

var concatArraysUniqueWithSort = function (thisArray, otherArray) {
    var newArray = thisArray.concat(otherArray).sort(function (a, b) {
        return a > b ? 1 : a < b ? -1 : 0;
    });

    return newArray.filter(function (item, index) {
        return newArray.indexOf(item) === index;
    });
};

请注意,自定义排序功能仅适用于数字元素,因此,如果您想将其用于字符串或将字符串与数字混合使用,则必须将其更新以考虑这些情况,尽管其余情况应该保持不变

Note that the custom sort function works with numeric elements only, so if you want to use it for strings or mix strings with numbers you have to update it off course to take those scenarios into account, though the rest should not change much.

像这样使用它:

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

var arrAll = concatArraysUniqueWithSort(arr1, arr2);

arrAll现在将是[1, 3, 4, 5, 6, 8, 9, 10]

演示 -连接2个数组,排序并删除重复项

DEMO - concatenate 2 arrays, sort and remove duplicates

我敢肯定有很多方法可以做到这一点.这只是我能想到的最简洁的方法.

There is many ways of doing this I'm sure. This was just the most concise I could think off.

这篇关于合并两个数组,存储唯一元素,并在jQuery中排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆