【问题标题】:How to slice the array elements between the stars如何对星星之间的数组元素进行切片
【发布时间】:2018-12-18 12:27:32
【问题描述】:

我需要帮助解决 y 问题,假设以下数组:

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

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

我可以使用过滤器找到所有*,但之后我可以使用indexOflastIndexOf 进行切片以获取第一个和最后一个*.indexOf(filteredElement,2) 我无法在之后搜索*具体数字,因为*的用户输入可以不同。

有什么建议吗?

提前谢谢大家

【问题讨论】:

  • 您可以添加您尝试过/正在使用的代码吗?
  • 您好斯图尔特。感谢您的回复。让 arr = [1,2,3,"" , 4, "" , 7 , 8 ,9 ,"", 10,11, "", 12 , ""];让过滤 = arr.filter(a => a == ""); let star0 = arr.indexOf(filtering[0]) let star1 = arr.indexOf(filtering[1]) let star2 = arr.indexOf(filtering[2]) console.log(star2) 这是我试过的代码
  • @Code - 输入数组有小的语法错误 - 接近“12 你忘了关闭引号 - 请更新你的问题

标签: javascript


【解决方案1】:

你可以用 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,2,3,"4",""]呢?我更新了您对确切 OP 问题的回答。
  • 干得好!想出了完全相同的解决方案,但你的速度更快
  • @Code Maniac 非常感谢先生。但是如果让 arr = ["1","2","3","" , 4, "" , 7 , 8 ,9 ,"", 10,11, "", 12, "*"];当数字是字符串时如何解决这个问题?
  • @Code 在更新的代码中检查 * 而不是数字。
  • 这对于连续的* 字符不起作用,例如["*",1,2,"*",7,8,9,"*","*",12,"*"]
【解决方案2】:

希望这会有所帮助,

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

【讨论】:

  • 不错! :) 它显然将数字转换为字符串,但这很容易解决。
【解决方案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,"*"]));

【讨论】:

    【解决方案4】:

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

    所以你匹配除了星星之外的所有东西,创建分组,然后用数字创建你的最终数组。

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

    【讨论】:

      【解决方案5】:

      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(["❤", "?", "?", "?", "?", "?"], "?"))

      【讨论】:

        【解决方案6】:

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

        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】:

          魔法(sn-p 中的解释)

          ((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.

          【讨论】:

            【解决方案8】:

            好的,我将使用数组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);

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2017-03-21
              • 2019-10-23
              • 1970-01-01
              • 2022-01-09
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多