Scotch Merge Arrays (v6)

Revision 6 of this benchmark created by Jayce Crowther on


Setup

// USING A SET
  function mergeArraysSet(...arrays) {
  
      let jointArray = []
      
      arrays.forEach(array => {
          jointArray = [...jointArray, ...array]
      });
  
      return [...new Set([...jointArray])]
  
  }
  
  // USING .FILTER()
  
  function mergeArraysFilter(...arrays) {
  
      let jointArray = []
      
      arrays.forEach(array => {
          jointArray = [...jointArray, ...array]
      })
  
      const uniqueArray = jointArray.filter((item,index) => jointArray.indexOf(item) === index)
  
      return uniqueArray
  }
  
  // USING .REDUCE()
  
  function mergeArraysReduce(...arrays) {
  
      let jointArray = []
      
      arrays.forEach(array => {
          jointArray = [...jointArray, ...array]
      })
  
      const uniqueArray = jointArray.reduce((newArray, item) =>{
          if (newArray.includes(item)){
              return newArray
          } else {
              return [...newArray, item]
          }
      }, [])
  
      return uniqueArray
  }
  // USING OBJECT
  const mergeUnique = (...arrays) => {
    let storedValues = {}
    let mergedArray = []
    const addValues = (array) => {
      array.forEach(item => {
        if(!storedValues[item.toString()]) {
          mergedArray.push(item)
          storedValues[item.toString()] = item
        }
      })
    }
    
    arrays.forEach(array => addValues(array))
    return mergedArray
  }

Test runner

Ready to run.

Testing in
TestOps/sec
Using .filter()
mergeArraysFilter(['a','b','z'],['m','n','a'],['z','y'])
ready
Using object
mergeUnique(['a','b','z'],['m','n','a'],['z','y'])
ready
Using sets
mergeArraysSet(['a','b','z'],['m','n','a'],['z','y'])
ready
Using .reduce()
mergeArraysReduce(['a','b','z'],['m','n','a'],['z','y'])
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 3: published by Cătălin Tănăsescu on
  • Revision 6: published by Jayce Crowther on
  • Revision 9: published by Volker Nauruhn on