我有几个要联合的数组,但我需要保持它们的顺序。示例:
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'
];和:
var js_files = [
'bower_components/jquery/dist/jquery.js',
'parnet/bower_components/jquery/dist/jquery.js',
'parent/bower_components/jquery.cookie/jquery.cookie.js'
];我希望将它们合并,并确保第一个数组将保留在第一个位置&删除重复的值。
预期输出:
['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来做这件事吗?还有别的主意吗?
发布于 2016-12-28 17:17:26
您可以使用Array.prototype.slice以ES5方式完成此操作,例如:
const first = [1,2,3,4];
const second = [5,6,7,8];
const results = [].concat(first.slice(), second.slice());或者是使用"desctructuring“的ESNext时尚
const first = [1,2,3,4];
const second = [5,6,7,8];
const result = [...first, ...second];编辑:我错过了你需要不同值的要点;
这将在您连接内容后从结果中删除重复项。
const distinctResults = results.filter(function removeDuplicates(item, index){
return results.indexOf(item) === index;
});发布于 2016-12-28 17:41:11
对于原始排序顺序中的唯一项,您可以将Set与spread syntax ...结合使用。
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);.as-console-wrapper { max-height: 100% !important; top: 0; }
发布于 2016-12-28 17:17:33
var a = [1,2,3];
var b = [4,5,6];
var Joined = [...a,...b];
同样,您的代码也可以这样做。
https://stackoverflow.com/questions/41358805
复制相似问题