如何在星空之间切片数组元素

时间:2018-12-18 12:27:33

标签: javascript

对于y问题,我需要帮助,假设使用以下数组:

let arr = [1,2,3,"*" , 4, "*" , 7 , 8 ,9 ,"*", "10","11", "*", "12" , "*"];

我想要这样的输出:
第一个数组[1,2,3],第二个数组[4],第三个数组[7,8,9],依此类推。

我可以找到所有带有过滤器的*,但是之后我可以只用indexOflastIndexOf切片以获得第一个和最后一个*.indexOf(filteredElement,2)我无法在*之后搜索*,因为return SingleChildScrollView( // horizontal scroll widget scrollDirection: Axis.horizontal, child: SingleChildScrollView( // vertical scroll widget scrollDirection: Axis.vertical, child: ...content of the container etc... ) ); 的用户输入可能不同。

有什么建议吗?

先谢谢大家

8 个答案:

答案 0 :(得分:6)

您可以通过reduce来做到这一点。

使用temp变量继续将值推入其中,直到找不到*为止;一旦找到*,则将此temp变量推入变量中output array并重置temp变量。

let arr = [1,2,3,"*" , 4, "*" , 7 , 8 ,9 ,"*", 10,11, "*", 12 , "*"];
let temp = []
let op = arr.reduce((o,c)=>{
  if(c !== '*'){
    temp.push(c)
  } else {
   if(temp.length){
    o.push(temp);
}
    temp=[];
  }
  return o;
},[])
console.log(op)

答案 1 :(得分:3)

您可以结合使用slice方法和while loop 语句。

function split_array(arr){
  let finalArr = [];
  i = 0;
  while(i < arr.length){
    j = i;
    
    while(arr[j] != "*"){ //find the sequence's end position.
      j++;
    }
    
    if(i!=j) //treat the case when first array item is *
      finalArr.push(arr.slice(i,j));
    
    while(arr[j] == "*"){ //skip consecutive * characters
      j++;
    }
    
    i = j;
  }
  return finalArr;
}
console.log(split_array([1,2,3,"*" , 4, "*" , 7 , 8 ,9 ,"*", 10,11, "*", 12 , "*"]));
console.log(split_array(["*",1,2,"*",7,8,9,"*","*",12,"*"]));

答案 2 :(得分:3)

希望这会有所帮助,

arr
    .join('|')
    .split('*')
    .filter((d) => d)
    .map((d) => d.split('|')
    .filter((d) => d));

答案 3 :(得分:2)

另一种解决方案是将数组视为字符串并与正则表达式匹配。

因此,您可以匹配除星星以外的所有内容,创建分组,然后使用数字创建最终数组。

const arr = [1, 2, 3, "*", 4, "*", 7, 8, 9, "*", 10, 11, "*", 12, "*"];

const res = arr.toString()
                .match(/[^*]+/g)
                .map(v => v.split(',')
                           .filter(v => v)
                           .map(v => +v));

console.log(res);

答案 4 :(得分:2)

使用forEach并进行一些过滤的另一种可能性:

const splitOnAsterisk = (arr) => {
  /* create an array to hold results with an initial empty child array */
  let result = [[]];
  /* create a new empty array in the result if current element is an asterisk,
     otherwise push to the last array in result… */
  arr.forEach(v =>
    v === "*"
    ? result.push([])
    : result[result.length - 1].push(v)
  );
  /* filter out empty arrays (if the first/last element was an asterisk
     or if there were two or more consecutive asterisks)
     [1, 2, "*", 3, "*"]
     ["*", 1, "*", 2, "*"]
     [1, 2, "*", "*", 3] etc…
  */
  return result.filter(a => a.length > 0);
}

console.log(splitOnAsterisk([1,2,3,"*",4,"*",7,8,9,"*",10,11,"*",12,"*"]))
console.log(splitOnAsterisk(["*",1,2,"*",7,8,9,"*","*",12,"*"]))
console.log(splitOnAsterisk(["*",1,"*","*",7,8,9,"*","*","*"]))

如果您需要的话,当然可以将其概括:

const splitArray = (arr, separator) => {
  let result = [[]];
  arr.forEach(v =>
    v === separator
    ? result.push([])
    : result[result.length - 1].push(v)
  );
  return result.filter(a => a.length > 0);
}

console.log(splitArray(["❤", "", "", "", "", ""], ""))

答案 5 :(得分:1)

魔术(摘要中的解释)

((r=[],i=0)=>(arr.map(x=>x=="*"?i++:(r[i]=r[i]||[]).push(x)),r))();

let arr = [1,2,3,"*" , 4, "*" , 7 , 8 ,9 ,"*", "10","11", "*", "12" , "*"];

let out = ((r=[],i=0)=>(   arr.map(x=> x=="*" ? i++ : (r[i]=r[i]||[]).push(x))   ,r))();

console.log(JSON.stringify(out));

// Explanation - we use arrow function to init two variables:
// r=[] and i=0
// then we use arr.map to iterate and check x=="*" if no
// then we put value to r[i], if yes then we increase i and ommit value.

答案 6 :(得分:1)

这是对数组进行分区的通用函数。与过滤器类似,它使用回调,使其用途广泛。

const partitionArray = (arr, separatorTest) => {
  const output = [];
  let curr = []; // keep track of the current partition

  arr.forEach(el => {
    if (separatorTest(el)) { // if we hit a partition split point
      output.push(curr); // push the partition to the output
      curr = []; // and set the current partition to an empty array for the next partition
    }
    else {
      curr.push(el); // add the current element to the partition
    }
  });

  return output;
}

// usage:
const arr = [1,2,3,'*',4,'*',7,8,9,'*',10,11,'*',12,'*'];
const splitArr = partitionArray(arr, el => el == '*');

答案 7 :(得分:0)

好的,我正在使用数组splice()方法来解决这个问题。这里的想法是使用while循环,并在每个循环上获取下一个token分隔符之前的元素数组。以这种方式使用的splice()方法将从原始数组中删除元素,因此我们可以使用数组的length作为停止条件。还要注意,完成循环所需的循环次数等于原始数组中的令牌分隔符数目。

let arr = [1, 2, 3, "*", 4, "*", 7, 8, 9, "*", "10", "11", "*", "12", "*"];
let result = [];
let token = "*";
let loopCounter = 0;

while (arr.length > 0)
{
    // Remove all elements from original array until find first token.
    // Push the removed array of elements inside the result.

    result.push(arr.splice(0, arr.indexOf(token)));

    // Remove a token separator from the array.

    arr.shift();
    loopCounter++;
}

console.log(JSON.stringify(result));
console.log(loopCounter);