我有一个字符串数组,有点像这样:
["x", "foo", "y", "bar", "baz", "z", "0"]
我需要数组拆分为每一个X,Y和Z或其他特殊的关键字也有。
我试着[x,y,z].split(y)
分裂数组,但我敢肯定split()
仅用于字符串。
关键字(X,Y,和Z)必须是在阵列中的第一个的。我怎样才能做到这一点?
这就是我试图得到:
[
["x", "foo"],
["y", "bar", "baz"],
["z", "0"]
]
你可以采取一个数组,并封闭了该键字符串指数,如果一个键被发现推空数组。
var array = ["x", "foo", "y", "bar", "baz", "z", "0"],
keys = ["x", "y", "z"],
result = array.reduce((i => (r, s) => {
if (s === keys[i]) {
r.push([]);
i++;
}
r[r.length - 1].push(s);
return r;
})(0), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
很简单!
const arr = ["x", "foo", "y", "bar", "baz", "z", "0"];
const specialChar = ['x', 'y', 'z'];
let result = [];
arr.forEach((el, index) => {
if(specialChar.includes(el)){
result.push([el, arr[index + 1]])
}
});
console.log(result)
const keywords = new Set(["x", "y", "z"]);
let acc = [];
const result = [];
for(const el of array) {
if(keywords.has(el)) {
result.push(acc = [el]);
} else acc.push(el);
}
我太晚了,但我会告诉其他的答案完全不同的方法。在这种方法中,输入阵列使用join()
转换为字符串,并使用,主要是,与split()
方法正则表达式可获得这样的结果:
const input = ["x", "foo", "y", "bar", "baz", "z", "0"];
const keyRegex = /(?=#x#)|(?=#y#)|(?=#z#)/;
let res = ("#" + input.join("#") + "#") // #x#foo#y#bar#baz#z#0#"
.split(keyRegex) // [#x#foo, #y#bar#baz, #z#0#]
.map(str => str.split("#").filter(Boolean));
console.log(JSON.stringify(res));
这里是使用map()
在与keys
数组的另一种方法。注意:我已经通过了input
数组的副本到map
方法,我用它作为this
参数。此外,我使用splice()
超过this
以除去已经分析部和findIndex()
通过缩短阵列执行期货。然而,没有这种事情可能比reduce()
或在输入阵列中的标准loop
的溶液更好。
const input = ["x", "foo", "y", "bar", "baz", "z", "0"];
const keys = ["x", "y", "z"];
let res = keys.map(function(k, i)
{
let a = this.findIndex(x => x === k);
let b = this.findIndex(x => x === keys[i+1]);
return this.splice(a, b >= 0 ? b : this.length);
}, input.slice());
console.log(JSON.stringify(res));
只是另一种方式来做到这一点。你可以使用slice
:
var a = ["x", "foo", "y", "bar", "baz", "z", "0"];
var breakpoints = ['x', 'y', 'z'];
var res = [];
for(var i = 0; i < breakpoints.length - 1; i++) {
res = res.concat([a.slice(a.indexOf(breakpoints[i]), a.indexOf(breakpoints[i+1]))]);
}
res = res.concat([a.slice(a.indexOf(breakpoints[i]))]);
console.log(res);
只是一个短期的替代那些已经公布,如果可以帮助很好的答案。
这是使用Array.reduce
:
const input = ['x', 'foo', 'y', 'bar', 'baz', 'z', '0'];
const keywords = ['x', 'y', 'z'];
const result = input.reduce((result, value) => {
keywords.includes(value) ? result.push([value]) : result[result.length - 1].push(value);
return result;
}, []);
console.log(result);
注意,如果输入数组中的第一项是不是关键字(它不应该是)将失败。你可以很容易地改变,否则到keywords.includes(value) || keywords.length === 0
的条件。
使用双减少有可能在第一阶段计算每个键的索引和在阵列第二减少分裂:
var arr = ["x", "foo", "y", "bar", "baz", "z", "0"];
var keys = keys = ["x", "y", "z"];
var retVal = arr.reduce(function(acc, ele, idx) {
if (keys.indexOf(ele) > -1) {
acc.push(idx);
}
return acc;
}, []).reduce(function(acc, ele, idx, a) {
acc.push(arr.slice(ele, a[idx+1]));
return acc;
}, []);
console.log(retVal);
您可以使用slice
由给定键的索引来提取单个阵列,并将其推入最后一个数组。
const arr = ["x", "foo", "y", "bar", "baz", "z", "0"];
function splitByKeys(...keys){
let splitarr = [];
for(let i =0; i<keys.length;i++){
if(i == keys.length -1 ){
splitarr.push(arr.slice( arr.indexOf(keys[i]) , arr.length));
}else{
splitarr.push(arr.slice( arr.indexOf(keys[i]) , arr.indexOf(keys[i+1])));
}
}
return splitarr;
}
console.log(splitByKeys("x", "y", "z"));
你可以通过下面的代码:
function separator(a) {
var result = [];
for (var i = 0; i < a.length; i++) {
var index = a[i].trim().toLowerCase();
switch (index) {
case "x":
case "y":
case "z":
if (result[index] == undefined) {
result.push([index]);
}
break;
default:
result[result.length - 1].push(a[i]);
}
}
return result;
}
// Sample:
var arr = ["x", "foo", "y", "bar", "baz", "z", "0"];
console.log(separator(arr));
// Result must be:
// [["x", "foo"], ["y", "bar", "baz"], ["z", "0"]]
或者用这个分组:
function separator(a) {
var result = {};
var lastIndex = "";
for (var i = 0; i < a.length; i++) {
var index = a[i].trim().toLowerCase();
switch (index) {
case "x":
case "y":
case "z":
if (result[index] == undefined) {
result[index] = [];
}
lastIndex = index;
break;
default:
result[lastIndex].push(a[i]);
}
}
return result;
}
// Sample:
var arr = ["x", "foo", "y", "bar", "baz", "z", "0"];
console.log(separator(arr));
// Result must be:
// {"x": ["foo"], "y": ["bar", "baz"], "z": ["0"]}
第二个代码可以工作在先进的阵列是这样的:
["x", "foo", "y", "bar", "x", "baz", "z", "0", "y", "bar2"]
And result is this:
{"x": ["foo", "baz"], "y": ["bar", "bar2"], "z": ["0"]}
const input = ['x', 'foo', 'y', 'bar', 'baz', 'z', '0'];
const keywords = ['x', 'y', 'z'];
input.reduce((prev, val) => {
const split = keywords.includes(val);
const index = prev.length - Number(!split);
prev[index] = split ? [val] : prev[index].concat(val)
return prev;
}, []);
这是应该做的分裂和避免不良的副作用的功能的方式。