JavaScript Set value at multidimensional array where dimensions are not pre-defined

心不动则不痛 提交于 2020-06-29 03:41:56

问题


Let's say I have an empty 1D array:

var data = [];

Now, I want to add value of 1 to data[1][1][3];

To do this, I need to extend data array to:

data = [

 [],
 [],
 [[],[],[1]]

]

Yeah, pretty sure that I have to write a function and pass dimension values as 1D array [1, 1, 3] and check 1. if there is second, third dimension and if 'no' create them and 2. if its size are greater or equal.

For just this example, function would be

function setData(value_, index_){

  if(data[index_[0]] == undefined){

    data = Array(index_[0] + 1).fill([]);
    data[index_[0]] = Array(index_[1] + 1).fill(1);
    data[index_[0]][index_[1]] = Array(index_[2] + 1).fill([]);
    data[index_[0]][index_[1]][index_[2]] = value_;

  }else{

    if(data[index_[0]][index_[1]] == undefined){

      data[index_[0]][index_[1]] = Array(index_[2] + 1).fill([]);
      data[index_[0]][index_[1]][index_[2]] = value_;

    }

  }

}

It's clumsy and straight-forward. How I can make an universal thing out of it? For any # of dimensions.

var data = [];

setData(false, [1, 1, 3]);

function setData(value_, index_){

  if(data[index_[0]] == undefined){

    data = Array(index_[0] + 1).fill([]);
    data[index_[0]] = Array(index_[1] + 1).fill(1);
    data[index_[0]][index_[1]] = Array(index_[2] + 1).fill([]);
    data[index_[0]][index_[1]][index_[2]] = value_;

  }else{

    if(data[index_[0]][index_[1]] == undefined){

      data[index_[0]][index_[1]] = Array(index_[2] + 1).fill([]);
      data[index_[0]][index_[1]][index_[2]] = value_;

    }

  }

}

console.log(data);

回答1:


this function might help you

var data = []

setData(false, [1, 1, 3])

function setData(value_, indexes_) {
  var currenLevelArr = data
  var len = indexes_.length
  // you can also use Foreach instead of  using for
  for (var i = 0; i < len; i++) {
    if (currenLevelArr[indexes_[i]] === undefined) {
      if (i === len - 1) {
        // we meet the target
        currenLevelArr[indexes_[i]] = value_
      } else {
        currenLevelArr[indexes_[i]] = []
        currenLevelArr = currenLevelArr[indexes_[i]]
      }
    } else if (Array.isArray(currenLevelArr[indexes_[i]])) {
      if (i === len - 1) {
        // we meet the target but
        //there is an extra dimension in the place
        //in which we want to set the value_
        console.error('something went wrong')
      } else {
        currenLevelArr = currenLevelArr[indexes_[i]]
      }
    } else {
      // the current position is filled with sth that we dont expect
      // if you want to replace the value ,you can add extra condition here
      console.error('something went wrong')
    }
  }
}

console.log(data)

this is the way you can trace the nodes object

var nodes = [

  {id: "1", x: 0, y: 0 },
  {id: "1.1", x: 0, y: 0 },
  {id: "1.1.1", x: 0, y: 0 },
  {id: "1.2", x: 1, y: 0 },
  {id: "1.3", x: 0, y: 1 },
  {id: "1.4", x: 1, y: 1 },
  {id: "1.3.1", x: 0, y: 0 },
  {id: "1.3.2", x: 0, y: 1 }

];

data = [];

nodes.forEach(function(node_){

var indices = node_.id.split(".");
indices = indices.map(function(d_){ return Number(d_) - 1; })
setData(true, indices);

});

function setData(value_, indexes_) {
  var currenLevelArr = data
  var len = indexes_.length
  for (var i = 0; i < len; i++) {
    if (currenLevelArr[indexes_[i]] === undefined) {
      currenLevelArr[indexes_[i]] = { value : undefined ,  subData : [] }
      if (i === len - 1) {
        currenLevelArr[indexes_[i]].value = value_ ;
      } else {
        currenLevelArr = currenLevelArr[indexes_[i]].subData;
      }
    } else  {
      if (i === len - 1) {
        currenLevelArr[indexes_[i]].value = 10 ;
      } else {
        currenLevelArr = currenLevelArr[indexes_[i]].subData
      }
    }
  }
}

function show(data , str="") {
  if(Array.isArray(data) ){
    for (var i = 0 ; i < data.length; i++ ) {
      if(data[i]) {
        if(data[i].value) {
          console.log(str + (i+1) + ": true" );
        } 
        show(data[i].subData , str + (i+1) + ",")
      }
    }
  }
}
show(data)
console.log(data);


来源:https://stackoverflow.com/questions/62199676/javascript-set-value-at-multidimensional-array-where-dimensions-are-not-pre-defi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!