0

I am having trouble iterating through a multidimensional array in TypeScript. In order to store the data into a db, I need to convert the multidimensional array into a one dimensional one.

My function:

storeDevices() {
    let tempDeviceList: Device[][] = this.dataStorageService.getDevices();
    console.log(tempDeviceList);
    console.log(tempDeviceList[1]);
    console.log(tempDeviceList[1][1]);
    console.log(tempDeviceList.length);
  }
console.log(tempDeviceList);

results in https://pastebin.com/mb2B9yrM I am using this as a lookup table which is why the first element is often null.

I do not understand why

    console.log(tempDeviceList[1]); //undefined
    console.log(tempDeviceList[1][1]); //undefined
    console.log(tempDeviceList.length); //0

result in undefined and 0. Because of this I am not able to iterate over the array. Based on the printed JSON, those elements should exist.

Vivida
  • 35
  • 4
  • Does this answer your question? [Merge/flatten an array of arrays](https://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays) – Heretic Monkey Jan 18 '22 at 20:42

2 Answers2

0

Converting a multi-dimensional array into a single dimensional one is also known as array flattening. There's plenty of resources on this topic, here's one on SO to get you started.

Jens Habegger
  • 5,266
  • 41
  • 57
  • Thanks for the suggestion. I tried various methods and they all return an empty array. I guess this is still related to my original problem described above. – Vivida May 12 '19 at 17:43
0
const data = [
  null,
  [
    null,
    {
      "deviceID": 1,
      "deviceType": 1,
      "updateFrequency": 1,
      "lastUpdate": 1557679860000,
      "payload": [
        22,
        31,
        32
        .... rest of your array data

Then you can create a Util class:

class Utils {
  public flatten(arr: any[]): any[] {
    // in node 11+, FF and Crome: 
    // return arr.flat();
    return [].concat(...arr);
  }

  // Use if you want to exclude null, undefined
  // or any falsey value from final array
  public compact(arr: any[]): any[] {
    return arr.filter(Boolean);
  }
}

const utils = new Utils();
const tempDeviceList = utils.compact(utils.flatten(data));


console.log(tempDeviceList[1]); // {deviceID: 2....
console.log(tempDeviceList.length); // 16

Read more about the new Array.prototype.flat()

makeitmorehuman
  • 11,287
  • 3
  • 52
  • 76
  • Alright now I am totally confused: When I manually define the data = [] like you did it works. When I use `let tempDeviceList: Device[][] = this.dataStorageService.getDevices();`, which printed is exactly the same as data, it does not work. Where is the difference? – Vivida May 12 '19 at 18:36
  • Maybe the return of your data call is Async and you need to await for it? What's in getDevices function? – makeitmorehuman May 12 '19 at 18:36