Skip to content Skip to sidebar Skip to footer

Compare A Array And An Object Array And Push The Contents Into The New Array According To The Value Specified

data = [ '1', '2','2] objlist = [ { name : 'dummy' } , {name: 'new' }, { name : 'news'},{name : 'place'}....] - 5 objects result = [ [{name:'dummy'}], [{name:'new'},{name:'news'}],

Solution 1:

You could push sliced parts to the result.

let array = [1, 2, 2],
    objlist = [{ name: 'dummy' }, { name: 'new' }, { name: 'news' }, { name: 'place' }, { name: 'place' }],
    result = [],
    i = 0,
    j = 0;
    
while (j < array.length) {
    result.push(objlist.slice(i, i += array[j++]));
}

console.log(result);

Solution 2:

You can loop through your array of numbers and for each number n use .splice(0, n) to get an array chunk from your array of objects. This will modify the array in-place, allowing your next .splice() to get the next consecutive object. For each .splice() you perform, you can .push() this into a resulting array.

See example below:

functionpartition([...arr], chunks) {
  const res = [];
  for(const n of chunks)
    res.push(arr.splice(0, n)); // +n to turn the string number into a number (splice will do this conversion for you but you can take care of it explicitly as well)return res;
}

const chunkArr = ['1', '2', '2'];
const arr = [{ name : 'dummy' }, {name: 'new' }, { name : 'news'},{name : 'place'}, {name : 'foo'}];

console.log(partition(arr, chunkArr));

Above I'm using partition([...arr], chunks) which uses the destructuring assignment syntax to perform a shallow copy of your input array. This way when you modify it inside your function using .splice(), it won't change the passed-in array.

Post a Comment for "Compare A Array And An Object Array And Push The Contents Into The New Array According To The Value Specified"