aderaaij
11/15/2017 - 3:53 PM

ES6 - Use `...` spread operator to modify / splice / merge arrays with obects

Combined with tools like Array.findIndex() and Array.slice() we can use the spread operator to easily modify an array and splice it into a new one with only the objects you want. You could also use this to create a new array by merging two arrays with specific values.

  
  const marvel = [
    { id: 4943, hero: 'Captain Marvel' },
    { id: 9854, hero: 'Luke Cage' },
    { id: 3943, hero: 'Iron Man' },
    { id: 1209, hero: 'Daredevil' },
    { id: 6592, hero: 'Mr. Fantastic' },
  ];
  
    
  const dc = [
    { id: 4943, hero: 'Batman' },
    { id: 9854, hero: 'Green Lantern' },
    { id: 3943, hero: 'Superman' },
    { id: 1209, hero: 'The Flash' },
    { id: 6592, hero: 'Aquaman' },
  ];
  
  // We've got a hero turned bad in our object, this is their id:
  const badHeroId = 3943;
  // With findIndex we can easily get the object index based on the ID
  const badHeroIndex = marvel.findIndex(hero => hero.id === badHeroId);
  // We use the index to slice the array twice: One time to get all the heroes from
  // 0 up to the bad hero, the second one to get all the heroes from the index after the 
  // bad hero up until the end (no argument); We immediately spread these out into the 
  // `newHeroes` array. 
  const newHeroes = [...marvel.slice(0, badHeroIndex), ...marvel.slice(badHeroIndex + 1)];
  console.log(newHeroes);
  
  // Now we'd love to combine some Marvel and DC superheroes into a new team:
  const marvelDC = [...marvel.slice(0, 3), ...dc.slice(3)];
  console.log(marvelDC)