Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to slice the array elements between the stars

Tags:

javascript

I need help for y problem, assume the following array:

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

I want to have an output like this:
first array [1,2,3], second array [4], third array [7,8,9] and so on.

I can find all the * with filter but after that I can slice just with indexOf and lastIndexOf to get the first and the last *.indexOf(filteredElement,2) I can't perform a search for * after specific number, because the user input of the * can be different.

Any suggestions?

Thanks in advance guys

like image 974
Code Avatar asked Dec 18 '18 12:12

Code


5 Answers

You can do it like this with reduce.

Use a temp variable keep on pushing value into it until you don't find a *, as soon as you find a * push this temp variable into output array and reset temp variable.

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)
like image 166
Code Maniac Avatar answered Oct 21 '22 06:10

Code Maniac


Hope this helps,

arr
    .join('|')
    .split('*')
    .filter((d) => d)
    .map((d) => d.split('|')
    .filter((d) => d));
like image 43
Praveenkumar Kalidass Avatar answered Oct 21 '22 05:10

Praveenkumar Kalidass


You could use slice method in combination with while loop statement.

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,"*"]));
like image 33
Mihai Alexandru-Ionut Avatar answered Oct 21 '22 06:10

Mihai Alexandru-Ionut


A different solution could be to treat the array as a string and match with a regex.

So you match everything but the stars, creating the groupings, and then create you final array with the numbers.

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);
like image 23
Alex G Avatar answered Oct 21 '22 05:10

Alex G


Another possibility with forEach and a bit of filtering:

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,"*","*","*"]))

This can of course be generalised if you need so:

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(["❀", "πŸš€", "πŸŽ„", "🐻", "πŸš€", "🐰"], "πŸš€"))
like image 25
helb Avatar answered Oct 21 '22 07:10

helb