Home > Software engineering >  Extract subarray from a multidimensional array and mutate the original array
Extract subarray from a multidimensional array and mutate the original array

Time:11-02

I want to extract a subarray from a multidimensional array and have the original array be mutated so it no longer contains the extracted subarray

If I have a multidimensional array called originalArray

I can extract a subarray from a list of header indices

function newArrCols(arrayofarray, indexlist) {
    return arrayofarray.map(function (array) {
        return indexlist.map(function (idx) {
            return array[idx];
        });
    });
}

So If:

idxList = [1,2,5,7]

subArray = newArrCols(originalArray, idxList)

Know I have to delete the subArray from the originalArray

//Remove columns from original arr w.r.t headeridx  
  for (var i = 0; i <= idxList.length - 1; i  ) {
         originalArray.map(a => a.splice(idxList[i], 1)); 
      }

Is there a way to do this in a single process I would like to skip the deleting part

Thanks

CodePudding user response:

EDIT:

Create a temporary empty array that will hold the items of the originalArray that aren't included in the idxList

let tempArray = [];

Create the subArray and populate the tempArray using Array.reduce():

let subArray = originalArray.reduce((accumulator, current, index) => {
    if (idxList.includes(index)) {
      //if the current index is included in the idxList array, 
      //push the current value to the accumulator
      accumulator.push(current);
    } else {
      //push the current value to the `tempArray`.
      tempArray.push(current)
    }
    return accumulator;
  }, []);

Replace the originalArray with a deep clone of the tempArray

originalArray = JSON.parse(JSON.stringify(tempArray));

Working snippet below.

Show code snippet

let originalArray = [
  [0, 0, 0, 0],
  [1, 1, 1, 1],
  [2, 2, 2, 2],
  [3, 3, 3, 3],
  [4, 4, 4, 4],
  [5, 5, 5, 5],
  [6, 6, 6, 6],
  [7, 7, 7, 7],
];

let idxList = [1, 2, 5, 7];
let tempArray = [];

//Can also be written in a one line arrow function
let subArray = originalArray.reduce((a, c, i) => (idxList.includes(i) ? a.push(c) : tempArray.push(c), a), []);

originalArray = JSON.parse(JSON.stringify(tempArray));

tempArray = [];

console.log({
  subArray: JSON.stringify(subArray)
});
console.log({
  originalArrayAfter: JSON.stringify(originalArray)
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related