Skip to content Skip to sidebar Skip to footer

How To Split An Array Into Multple Arrays Each With A Unique Name

I have an array = [A,1,0,1,0,1,B,1,0,0,1,A,1] I need to split this array into multiple arrays. The split will occur at the 'A' or 'B' position as seen in the new arrays below. The

Solution 1:

It seems like you're trying to dynamically create variables. That seems tricky and probably won't work. What you should probably have is some collection of results. Probably a parent array that holds all of them.

For example:

var containerArray = [];

Then:

for (var i = 0; i < arr.length; i++){
    sectArray = arr.slice(arrTemp[i]+1,arrTemp[i + 1])
    containerArray[i] = [arrTemp[i],sectArray];
}

Now containerArray will have all of your stuff. You can also do this with an object:

var containerObject = {};

And the same thing after.

Solution 2:

you only need one loop here, keep an empty temp array, iterate over arr and keep pushing elements in temp each time you see 'A' or 'B' push temp to final array, and at last push temp once more into final array because last section will be left.

var arr = ['A',1,0,1,0,1,'B',1,0,0,1,'A',1];
var temp = [];
var sectArray = [];
arr.forEach(myFunction)
functionmyFunction(item, index)    {
if (((item=="A") || (item=="B")) && temp.length) {
sectArray.push(temp);
temp = [item];
}else{
 temp.push(item);
}
}
sectArray.push(temp);
console.log(sectArray);

Solution 3:

Check this solution that use a combination of string and array methods:

var data = ['A',1,0,1,0,1,'B',1,0,0,1,'A',1];

var results = data.toString().split(/(?=[a-zA-Z]+)/)
.map(function(value){
  return value.split(',').filter(function (item) {
    return item.length ? true: false;
  })
})
.map(function(item) {
   return item.map(function (value) {
     returnisNaN(parseInt(value)) ? value : parseInt(value);
   })
});

console.log(results);

// results = [["A", 1, 0, 1, 0, 1], ["B", 1, 0, 0, 1], ["A", 1]]

enter image description here

Solution 4:

Another solution using Array#reduce function.

var x = ["A", 1, 0, 1, 0, 1, "B", 1, 0, 0, 1, "A", 1];


functionreformat(arr) {
    var smallArrCounter = 0;
    return arr.reduce(function (acc, item) {
        if (item === "A" || item === "B") {
            acc["group" + (++smallArrCounter)] = [item];
        } else {
            acc["group" + smallArrCounter].push(item);
        }
        return acc;
    }, {});
}

var result =  reformat(x);

console.log(result.group1); // ["A",  1,  0,  1,  0,  1]console.log(result.group2); // ["B",  1,  0,  0,  1]console.log(result.group3); // ["A", 1]

Solution 5:

There may be a more performant approach that doesn't require two iterations of the array, but my thought is:

  1. Determine the indices of the group delimiters (characters)
  2. Slice the array into groups based on those delimiters, using either the next index as the end, or arr.length if slicing the last group

This has the assumption that the array delimiters may not be known in advance.

const charIndices = [];
const groups = [];
const arr = ['A',1,0,1,0,1,'B',1,0,0,1,'A',1];
// get the indices of the characters
arr.forEach((v, i) => ('' + v).match(/[A-Z]+/) ? charIndices.push(i) : undefined);
// use the found indices to split into groups
charIndices.reduce((a, b, i) => {
   a.push(arr.slice(b, charIndices[i+1] ? charIndices[i+1]-1 : arr.length));
   return a;
}, groups);
console.log(groups);

Post a Comment for "How To Split An Array Into Multple Arrays Each With A Unique Name"