Разделить jsonarray на массивы чанков в другой массив - PullRequest
0 голосов
/ 30 мая 2018

Я пытаюсь разбить массив сына на куски из 3 внутренних массивов.

ex:

[{
  title: "asd",
  description: "asd"
}, {
  title: "asz",
  description: "sd"
}, {
  title: "ws",
  description: "sd"
}, {
  title: "re",
  description: "sd"
}, {
  title: "32",
  description: "xxs"
}, {
  title: "xxc",
  description: "11"
}]

Я хочу преобразовать массив верхнего сына в куски, как показано ниже

[
  [{
    title: "asd",
    description: "asd"
  }, {
    title: "asz",
    description: "sd"
  }, {
    title: "ws",
    description: "sd"
  }],
  [{
    title: "re",
    description: "sd"
  }, {
    title: "32",
    description: "xxs"
  }, {
    title: "xxc",
    description: "11"
  }]
]

Я пробовал подобный пример, но он работает для этого массива ['a','b','c','d','e'] отлично.ниже приведен код, который я пробовал,

perChunk = 2 // items per chunk    

inputArray = ['a', 'b', 'c', 'd', 'e']

inputArray.reduce((resultArray, item, index) => {
  const chunkIndex = Math.floor(index / perChunk)

  if (!resultArray[chunkIndex]) {
    resultArray[chunkIndex] = [] // start a new chunk
  }

  resultArray[chunkIndex].push(item)

  console.log(resultArray)
  return resultArray

}, [])

Но для моего ввода это не работает.

Пожалуйста, подскажите, как мне этого добиться

Ответы [ 5 ]

0 голосов
/ 30 мая 2018

Следующий фрагмент splits arrays в chunks от size.

Array.prototype.filter() используется для omit нежелательных elements (even numbers) из input array.

Array.prototype.slice и for statement объединяются для создания chunks без mutating оригинала input array.

Leftovers включается как окончательный chunk в output, когда это уместно.

// Input.
const input = [1, 2, 3, 4, 5, 6, 7, 8, 9].filter(x => x % 2)

// Chunk.
const chunk = (array, size) => {
  let output = []
  let i = 0
  const max = array.length + (array.length % size) + 1
  for (let j = size; j < max; j += size) {
    output.push(array.slice(i, j))
    i = j
  }
  return output
}

// Output / Proof.
console.log('chunk size: 1', chunk(input, 1))
console.log('chunk size: 3', chunk(input, 3))
console.log('chunk size: 5', chunk(input, 5))
0 голосов
/ 30 мая 2018

Попробуйте что-то подобное:

const chucnk = (array, chunckSize) =>
  array.reduce(
    (a, b, i, g) =>
      !(i % chunckSize) ? a.concat([g.slice(i, i + chunckSize)]) : a,
    []
  );

const array = [{
  title: "asd",
  description: "asd"
}, {
  title: "asz",
  description: "sd"
}, {
  title: "ws",
  description: "sd"
}, {
  title: "re",
  description: "sd"
}, {
  title: "32",
  description: "xxs"
}, {
  title: "xxc",
  description: "11"
}]

chunck(array,3);
0 голосов
/ 30 мая 2018

Вы можете разбить массив на заданное количество кусков

split(arr, n) {
        var res = [];
        while (arr.length) {
            res.push(arr.splice(0, n));
        }
        return res;
    }

Использование

 var arrayFregments = split(myArray, 3); //no of chunks
 var requests = arrayFregments.reduce((promiseChain, item) => {
            return promiseChain.then(() => new Promise((resolve) => {
                 asyncFunction(item, resolve); //some async function
            }));
        }, Promise.resolve());

 requests.then(() => {
               // after requests has been completed.
            });

Обновление

Если вы хотите удалить пустой объект данных, вы можете использовать фильтр

mainList = mainList.filter(function(item){
        return item.title.trim().length>0 && item.description.trim().length>0

});
console.log(mainList)

Пример - http://jsfiddle.net/zj1pe7q3/3/

0 голосов
/ 30 мая 2018

Разбить массив на куски необходимого размера:

var arr = [{
  title: "asd",
  description: "asd"
}, {
  title: "asz",
  description: "sd"
}, {
  title: "ws",
  description: "sd"
}, {
  title: "re",
  description: "sd"
}, {
  title: "32",
  description: "xxs"
}, {
  title: "xxc",
  description: "11"
}]

var i, j, resArray=[], chunk = 2;
for (i = 0, j = arr.length; i < j; i += chunk) {
  resArray.push(arr.slice(i, i + chunk));
}

console.log(resArray);
0 голосов
/ 30 мая 2018
// Chunk a single array into multiple arrays, each containing `count` or fewer
  // items.
function chunk(array, count) {
    if (count == null || count < 1) return [];
    var result = [];
    var i = 0, length = array.length;
    while (i < length) {
      result.push(Array.prototype.slice.call(array, i, i += count));
    }
    return result;
  };

Использование:

var newList = chunk(mainList, 2);

Демонстрационная скрипка


ИЛИ

Вы можете использовать кусок подчеркивания или lodash

var mainList = [
  {
    "title": "asd",
    "description": "asd"
  },
  {
    "title": "asz",
    "description": "sd"
  },
  {
    "title": "ws",
    "description": "sd"
  },
  {
    "title": "re",
    "description": "sd"
  },
  {
    "title": "32",
    "description": "xxs"
  },
  {
    "title": "xxc",
    "description": "11"
  }
];

var newList = _.chunk(mainList, 2);

Вывод:

[
  [
    {
      "title": "asd",
      "description": "asd"
    },
    {
      "title": "asz",
      "description": "sd"
    }
  ],
  [
    {
      "title": "ws",
      "description": "sd"
    },
    {
      "title": "re",
      "description": "sd"
    }
  ],
  [
    {
      "title": "32",
      "description": "xxs"
    },
    {
      "title": "xxc",
      "description": "11"
    }
  ]
]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...