DEV Community

Cover image for JS Hack: Array & Duplicate Values
Renato Byrro for Dashbird

Posted on

JS Hack: Array & Duplicate Values

This week's hack is about cleaning duplicate values from Arrays

The Neat Dev version:

let myArr = ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']

console.log([...new Set(myArr)])

// Outputs: (7) ["h", "e", "l", "o", "w", "r", "d"]

The Ninja Dev version:

Because, why not add 15 lines of code and useless comments, right!?

let u = [], a = ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']

for(z in a) {
  let t = false

  // Because a for loop is always better than Array.includes()
  for(g in u) {
    // Ninjas reap maximum benefit from IF statements
    if(a[z] === u[g]) // Readability matters
      t = true
  }

  // See? The more IFs, the better
  if(!t)
    u.push(j)
}

console.log(u)

// Outputs: the same, but a little more tired of typing

Top comments (2)

Collapse
 
khuongduybui profile image
Duy K. Bui

Ninja code is bad - scratch that, legendary - in their readability and maintainability, not performance.

A true ninja would write

$: for(z in a) {

$$: for(g in u) {

and

break $$

Collapse
 
byrro profile image
Renato Byrro

True 😄