如何动态拆分数组?

时间:2019-02-02 16:52:23

标签: javascript arrays split

我有一个字符串数组,有点像这样:

["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"]
]

10 个答案:

答案 0 :(得分:11)

您可以为键字符串的索引获取一个数组和一个闭包,如果找到键,则推送一个空数组。

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; }

答案 1 :(得分:6)

 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);
 }

答案 2 :(得分:3)

我来不及了,但是我将展示与其他答案完全不同的方法。在这种方法中,输入阵列使用转换成字符串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));

答案 3 :(得分:2)

这是另一种方式。您可以使用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);

答案 4 :(得分:1)

如果可以的话,只是已发布好的答案的简短替代方案。

这正在使用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

答案 5 :(得分:1)

在第一阶段计算每个键的索引,然后在第二次reduce拆分数组时,可以使用double reduce:

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);

答案 6 :(得分:1)

您可以通过以下代码进行操作:

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"]}

答案 7 :(得分:1)

您可以使用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"));

答案 8 :(得分:1)

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;
}, []);

这是进行拆分并避免不良副作用的一种实用方法。

答案 9 :(得分:1)

非常简单!

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)