Scotch Merge Arrays

JavaScript performance comparison

Revision 6 of this test case created by Jayce Crowther

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  // 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
  }
  

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Using .filter()
mergeArraysFilter(['a','b','z'],['m','n','a'],['z','y'])
pending…
Using object
mergeUnique(['a','b','z'],['m','n','a'],['z','y'])
pending…
Using sets
mergeArraysSet(['a','b','z'],['m','n','a'],['z','y'])
pending…
Using .reduce()
mergeArraysReduce(['a','b','z'],['m','n','a'],['z','y'])
pending…

Compare results of other browsers

Revisions

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

0 Comments