Convert nested arrays to one-dimensional array in MS Office Script

71 Views Asked by At

Hi I need to convert this:

// Convert [[1],[2],[3],[4],["a","b","c"],["d","e","f"]]

to this:

[1,2,3,4,"a","b","c","d","e","f"]

In MS Office Script. I can't use

I've tried using things like array.flat(), but it doesn't exist in Office Script.

2

There are 2 best solutions below

0
Dev Kraken On

Try something like that may be it's help

const fixPattern = (inputArray) => {
  let newArray = [];

  for (var i = 0; i < inputArray.length; i++) {
    const currentElement = inputArray[i];

    if (Array.isArray(currentElement)) {
      for (let j = 0; j < currentElement.length; j++) {
        newArray.push(currentElement[j]);
      }
    } else {
      newArray.push(currentElement);
    }
  }

  return newArray;
}

const inputArray = [
  [1],
  [2],
  [3],
  [4],
  ["a", "b", "c"],
  ["d", "e", "f"]
];
const result = fixPattern(inputArray);
console.log(result);

0
Normal On

const givenArray = [[1], [2], [3], [4], ["a", "b", "c"], ["d", "e", "f"]]

function flattenArray(arr) {
  return arr.reduce((result, el) => {
    return result.concat(Array.isArray(el) ? flattenArray(el) : el)
  }, [])
}

const givenArrayFlattened = flattenArray(givenArray)
console.log(givenArrayFlattened)