首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将两个具有排序的数组合并?

问如何将两个具有排序的数组合并?
EN

Stack Overflow用户
提问于 2016-12-28 17:12:54
回答 6查看 137关注 0票数 0

我有几个要联合的数组,但我需要保持它们的顺序。示例:

代码语言:javascript
复制
var js_files = [
'bower_components/jquery/dist/jquery.js',
'bower_components/jquery.cookie/jquery.cookie.js',
'bower_components/jquery-placeholder/jquery-placeholder.js',
'bower_components/foundation-sites/dist/foundation.js',
'bower_components/Swiper/dist/js/swiper.jquery.min.js',
'assets/scripts/**/*.js'
];

和:

代码语言:javascript
复制
var js_files = [
'bower_components/jquery/dist/jquery.js',
'parnet/bower_components/jquery/dist/jquery.js',
'parent/bower_components/jquery.cookie/jquery.cookie.js'
];

我希望将它们合并,并确保第一个数组将保留在第一个位置&删除重复的值。

预期输出:

代码语言:javascript
复制
['bower_components/jquery/dist/jquery.js',
'bower_components/jquery.cookie/jquery.cookie.js',
'bower_components/jquery-placeholder/jquery-placeholder.js',
'bower_components/foundation-sites/dist/foundation.js',
'bower_components/Swiper/dist/js/swiper.jquery.min.js',
'assets/scripts/**/*.js',
'parnet/bower_components/jquery/dist/jquery.js',
'parent/bower_components/jquery.cookie/jquery.cookie.js']

我可以使用_.union来做这件事吗?还有别的主意吗?

EN

回答 6

Stack Overflow用户

发布于 2016-12-28 17:17:26

您可以使用Array.prototype.slice以ES5方式完成此操作,例如:

代码语言:javascript
复制
const first = [1,2,3,4];
const second = [5,6,7,8];

const results = [].concat(first.slice(), second.slice());

或者是使用"desctructuring“的ESNext时尚

代码语言:javascript
复制
const first = [1,2,3,4];
const second = [5,6,7,8];

const result = [...first, ...second];

编辑:我错过了你需要不同值的要点;

这将在您连接内容后从结果中删除重复项。

代码语言:javascript
复制
const distinctResults = results.filter(function removeDuplicates(item, index){

  return results.indexOf(item) === index;
});
票数 1
EN

Stack Overflow用户

发布于 2016-12-28 17:41:11

对于原始排序顺序中的唯一项,您可以将Set与spread syntax ...结合使用。

​

代码语言:javascript
复制
var js_files1 = [
    'abc',
    'def',
    'bower_components/jquery/dist/jquery.js',
    'bower_components/jquery.cookie/jquery.cookie.js',
    'bower_components/jquery-placeholder/jquery-placeholder.js',
    'bower_components/foundation-sites/dist/foundation.js',
    'bower_components/Swiper/dist/js/swiper.jquery.min.js',
    'assets/scripts/**/*.js'
  ],
  js_files2 = [
    'def',
    'ghi',
    'bower_components/jquery/dist/jquery.js',
    'parnet/bower_components/jquery/dist/jquery.js',
    'parent/bower_components/jquery.cookie/jquery.cookie.js'
  ],
  uniqueFiles = [...new Set([...js_files1, ...js_files2])];

console.log(uniqueFiles);
代码语言:javascript
复制
.as-console-wrapper { max-height: 100% !important; top: 0; }

​

票数 1
EN

Stack Overflow用户

发布于 2016-12-28 17:17:33

​

代码语言:javascript
复制
var a = [1,2,3];
var b = [4,5,6];

var Joined = [...a,...b];

​

同样,您的代码也可以这样做。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41358805

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档