给定数组:
var arr = ['', 'foo', '', 'bar', '', 'baz', ''];
我想回来:
[ 'foo', 'bar', 'baz', '', '', '', '' ]
答案 0 :(得分:5)
我会使用自定义排序功能,如下所示:
['', 'foo', '', 'bar', '', 'baz', ''].sort((a, b) => !a ? 1 : !b ? -1 : 0);
// returns: ["foo", "bar", "baz", "", "", "", ""]
答案 1 :(得分:0)
一种非ES6方式是:
var arr = ['', 'foo', '', 'bar', '', 'baz', ''];
arr = arr.filter(function(val){return val}).concat(arr.filter(function(val){return !val}));
或者,使用ES6缩短内容:
arr = arr.filter((val) => val).concat(arr.filter((val) => !val));
答案 2 :(得分:0)
性能可疑,但是:
var arr = ['', 'foo', '', 'bar', '', 'baz', ''];
arr.forEach((v, i) => v || (arr.splice(i, 1), arr.push(v)) );
console.log(arr)
当然,没有调整大小或创建额外数组的就地交换解决方案会更有效:
var arr = ['', 'foo', '', 'bar', '', 'baz', ''];
for (var i = 0, j = arr.length - 1, v; ; ++i, --j) {
while (arr[i]) ++i
while (!arr[j]) --j
if (i >= j) break
v = arr[i]
arr[i] = arr[j]
arr[j] = v
}
console.log(arr)
或保留订单:
var arr = ['', 'foo', '', 'bar', '', 'baz', '']
for (var i = 0, j = 1, len = arr.length, v; ; ++i, ++j) {
while (arr[i]) ++i
while (!arr[j] && j < len) ++j
if (j >= len) break
v = arr[i]
arr[i] = arr[j]
arr[j] = v
}
console.log(arr)