所以可以说我有这个数组var:
arr = ["a","b","c","d","a","b","a","b","a"]
以此类推a
的出现只是随机的
我想将此数组从一个a
划分到下一个a
例如,我的新数组可能像
[["a","b","c","d"],["a","b"],["a","b"],["a"]]
答案 0 :(得分:3)
如果具有所需的值,则可以缩小数组并将新的数组推入结果。然后将所有值推入结果集中的最后一个数组。
var array = ["a", "b", "c", "d", "a", "b", "a", "b", "a"],
result = array.reduce((r, v, i) => {
if (!i || v === 'a') r.push([]);
r[r.length - 1].push(v);
return r;
}, []);
console.log(result);
答案 1 :(得分:1)
您可以将数组转换为字符串,然后使用match()
和RegExp
。然后使用map()
获取数组数组
let arr = ["a","b","c","d","a","b","a","b","a"]
let res = arr.join('').match((/a[^a]+/g)).map(x => [...x]);
console.log(res)
答案 2 :(得分:0)
您可以使用split()/join()
这样的方法来做到这一点:
let arr = ["a", "b", "c", "d", "a", "b", "a", "b", "a"];
let r = arr.join('').split('a').map(x => (["a", ...x.split('')]));
r.shift();
console.log(r);
答案 3 :(得分:0)
一种简洁的方法是将您的字符连接成字符串,然后使用正向超前正则表达式在每个a
上进行拆分,以将a
保留在拆分的部分中,最后将所得的部分拆分为数组:
const arr = ["a","b","c","d","a","b","a","b","a"];
const result = arr.join('').split(/(?=a)/).map(x => x.split(''));
console.log(JSON.stringify(result));
答案 4 :(得分:0)
您可以执行以下操作。
首先将数组转换为字符串:-"abcdababa" (using .join(""))
现在使用“ a”作为分隔符分割字符串:-["","bcd","b","b",""] (using .split("a"))
现在在所有元素前添加“ a”:-["a","abcd","ab","ab","a"] (using .map(x=>"a"+x))
现在使用“”(空字符串)作为分隔符分割所有元素:-[["a"],["a","b","c","d"],["a","b"],["a","b"],["a"]] (using .split("")) (this step will be inside map function)
现在删除第一个元素(因为它不是字符串的一部分):-[["a","b","c","d"],["a","b"],["a","b"],["a"]] (using .shift())
var arr = ["a","b","c","d","a","b","a","b","a"];
var x1 = arr.join("").split("a").map(x => {
x = "a" + x;
return x.split("");
});
x1.shift();
console.log(x1);
答案 5 :(得分:0)
使用简单的forEach
var arr = ["a", "b", "c", "d", "a", "b", "a", "b", "a"];
var result = [];
var i = -1;
arr.forEach(function(val) {
if (val == 'a') {
result.push([]);
i++;
}
result[i].push(val);
})
console.log(result);