Split array into two arrays

前端 未结 9 928
甜味超标
甜味超标 2020-12-24 10:24
var arr = [\'a\', \'b\', \'c\', \'d\', \'e\', \'f\'];
var point = \'c\';

How can I split the \"arr\" into two arrays based on the \"point\" variabl

相关标签:
9条回答
  • 2020-12-24 11:22

    Try this one:

    var arr = ['a', 'b', 'c', 'd', 'e', 'f'];
    var point = 'c';
    
    var idx = arr.indexOf(point);
    
    arr.slice(0, idx) // ["a", "b"]
    arr.slice(idx + 1) // ["d", "e", "f"]
    
    0 讨论(0)
  • 2020-12-24 11:25

    When splitting the array you are going to want to create two new arrays that will include what you are splitting, for example arr1 and arr2. To populate this arrays you are going to want to do something like this:

    var arr1, arr2; // new arrays
    int position = 0; // start position of second array
       for(int i = 0; i <= arr.length(); i++){
           if(arr[i] = point){ //when it finds the variable it stops adding to first array
               //starts adding to second array
                for(int j = i+1; j <= arr.length; j++){
                   arr2[position] = arr[j];
                   position++; //because we want to add from beginning of array i used this variable
                }
           break;
           }
          // add to first array
           else{
               arr1[i] = arr[i];
           }
    }
    

    There are different ways to do this! good luck!

    0 讨论(0)
  • 2020-12-24 11:26
    var arr2 = ['a', 'b', 'c', 'd', 'e', 'f'];
    arr = arr2.splice(0, arr2.indexOf('c'));
    

    To remove 'c' from arr2:

    arr2.splice(0,1);
    

    arr contains the first two elements and arr2 contains the last three.

    This makes some assumptions (like arr2 will always contain the 'point' at first assignment), so add some correctness checking for border cases as necessary.

    0 讨论(0)
提交回复
热议问题