Организовать массив на основе другого массива Javascript - PullRequest
0 голосов
/ 30 ноября 2018

У меня есть ссылочный массив, который имеет значения ["a","b","c","d"]. И у меня есть другой массив, который получается как часть API, который не является очень согласованным форматом. Я приведу несколько примеров ниже

case 1.`{
     names : ["a"],
     value : [ [0],[0],[2],[4],... ]
   }`
case 2. `{
     names : ["a","c"],
     value : [ [0,2],[0,0],[2,3],[4,4],... ]
    }`

результатможет быть в любой комбинации, но мое требование состоит в том, чтобы присвоить значение входящего результата в другой массив, индекс которого такой же, как у моего ссылочного массива, например: в случае 1

`
let finalArray = [["0",null,null,null],
                  ["0",null,null,null], 
                   ["2",null,null,null]....  ]
`

для случая 2:

`let finalArray = [["0",null,"2",null],
                  ["0",null,"0",null], 
                   ["2",null,"3",null]....   ]  
`

также прикрепление скрипты с моими данными ниже

jsfiddle ссылка на проблему

есть предложения?я пытаюсь использовать минимальный цикл для оптимизации производительности

Ответы [ 2 ]

0 голосов
/ 30 ноября 2018

Ниже я могу подумать, что для этого потребуется минимум итераций.

    var refArray = ["a", "b", "c", "d"];
    setTimeout(()=>{processResult({
         "names" : ["a"],
         "value" : [ [0],[0],[2],[4]]
       })},2000);
    setTimeout(()=>{processResult(
    {
         "names" : ["a","c"],
         "value" : [ [0,2],[0,0],[2,3],[4,4]]
    })},4000);
    setTimeout(()=>{processResult(
    {
         "names" : ["d","c"],
         "value" : [ [0,2],[0,0],[2,3],[4,4]]
    })},6000);


    function processResult(result) {
      //This map will contain max names matched in the result
      var maxItemsFromResult = {};

      //Find the indexes in refArray and fill map
      //e.g. 1st- {0:0}, 2nd - {0:0, 1:2}, 3rd - {0:3, 1:2}
      result.names.forEach((item, index) => {
        let indexFound = refArray.indexOf(item);
        if (indexFound > -1) {
          maxItemsFromResult[index] = indexFound;
        }
      });

      //for performance if no key matched exit
      if (Object.keys(maxItemsFromResult).length < 1) {
        return;
      }
      //This will be final result
      let finalArray = [];

      //Because finalArray's length shuld be total items in value array loop through it
      result.value.forEach((item, itemIndex) => {
        //Create a row
        let valueArray = new Array(refArray.length).fill(null);
        //Below will only loop matched keys and fill respective position/column in row
        //i'm taking all the matched keys from current value[] before moving to next
        Object.keys(maxItemsFromResult).forEach((key, index) => {
          valueArray[maxItemsFromResult[key]] = item[index];//get item from matched key
        });
        finalArray.push(valueArray);
      });
      console.log(finalArray);
      return finalArray;
    }
0 голосов
/ 30 ноября 2018

Надеюсь, это будет полезно.

var refArray = ["a","b","c","d"];

setTimeout(()=>{processResult({
     "names" : ["a"],
     "value" : [ [0],[0],[2],[4]]
   })},2000);
setTimeout(()=>{processResult(
{
     "names" : ["a","c"],
     "value" : [ [0,2],[0,0],[2,3],[4,4]]
})},4000);
setTimeout(()=>{processResult(
{
     "names" : ["d","c"],
     "value" : [ [0,2],[0,0],[2,3],[4,4]]
})},6000);


function processResult (result) {
    let res = result.value;
    let resArray = res.map((el)=>{
        let k=Array(refArray.length).fill(null);
        refArray.forEach((e,i)=>{
          let indx = result.names.indexOf(e);
          if(indx>=0){      	
                k[i] = el[indx]
            }      
        });
        return k;
    })
  console.log("result",resArray)	
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...