skip to Main Content

I’m a beginner of javascript.

Please see below example about removing duplicate value from

const nums = [1, 2, 3, 6, 6, 7, 2, 2, 8, 9]

function uniqueNums(arr) {
  const uniqueElements = {};
  const result = [];
  for (let element of arr) {
    if (!uniqueElements[element]) {
      result.push(element)
    }
    uniqueElements[element] = element // this part I don't understand.
  }
  return result;
}

console.log(uniqueNums(nums)) // [1,2,3,6,7,2,8,9]

I don’t understand the role of the following statement:

uniqueElements[element] = element 

If I remove the line,

const nums = [1, 2, 3, 6, 6, 7, 2, 2, 8, 9]

function uniqueNums(arr) {
  const uniqueElements = {};
  const result = [];
  for (let element of arr) {
    if (!uniqueElements[element]) {
      result.push(element)
    }
    // uniqueElements[element] = element // this part I don't understand.
  }
  return result;
}

console.log(uniqueNums(nums)) // [1,2,3,6,7,2,8,9]

I can see the return value that duplicated value isn’t removed.
why..?

Isn’t it the below the conditional statement about duplicate value..?
if(!uniqueElements[element])

I know the easy way to solve is using ‘set’, the more I learn javascript, the more I have difficulties with objects, so I practice and practice.

4

Answers


  1. uniqueElements is defined as an object {}.

    Objects have unique keys. And they are strings so the key is converted to string

    When you do uniqueElements["2"] = 2

    Then next time you do

    uniqueElements["2"] = 2

    the entry for "2" will be overwritten

    It is a rather simple and inefficient implementation of a Set

    // the Set removes the duplicates. The [...Set] "spreads" the Set to an array
    const uniqueNums = arr => [...new Set(arr)]; 
    console.log(uniqueNums([1, 2, 3, 4, 3, 2, 1]));

    Here is a version that does not use a Set

    const uniqueNums = arr => {
      const uniqueElements = {};
      arr.forEach(element => uniqueElements[element] = element); // same as your uniqueElements[element] = element
      return Object.values(uniqueElements); // return just the values - Object.keys would return an array of strings
    }
    console.log(uniqueNums([1, 2, 3, 4, 3, 2, 1]))
    Login or Signup to reply.
  2. In JavaScript, an object is basically a map of key-value pairs. The key can have data type string or Symbol. Understanding of Symbol data type is not required for this question. So the key can be a string. But you can also specify a number and it will be stored as a string. You can use [] to index into an object. I have quoted the key name but that is not necessary when creating the object. the quotes are needed for keys having special characters, starting with a digit etc. For example '1' and `’last-name“.

    const map = {
        'name': 'John',
        '1': 1,
        'last-name': 'Doe'
    }
    

    When accessing object properties, the . operator can be used.

    console.log( john.name );
    

    However for keys with special characters, or a digit as the first character, you need to use [].

    console.log( john['1'] );
    console.log( john['last-name'] );
    

    Further for keys that represent numbers (like '1' ), we can simply use the number to index, and the number is converted to a string internally.

    console.log( john[1] ); // is same as...
    console.log( john['1'] ); // ...this
    

    Further, keys in an object cannot have duplicates. If you assign a value for a key that exists, the new value replaces the old value. In your problem, this fact is being used. I think you will be able to figure out how your code works now. If you still have a question, please post a comment, and I’ll update this answer.

    Login or Signup to reply.
  3. In your function, the line uniqueElements[element] = element is an object used to keep track of all the elements that have been looped. The if (!uniqueElements[element]) {} block checks if the current element is NOT in that object and pushed the element to the result array. If you are looking for a real solution do use one of solutions given by @mplungjan or use a library like lodash. But if you are using this for learning, just know that there are better ways to do this. Also, in your function there is no need for the if (!uniqueElements[element]) {}. Try returning Object.keys(uniqueElements)

    Login or Signup to reply.
  4. Hello Beginner!

    Welcome to the JS land 🚀

    First off, objects are a wonderful way to store complex data models. When it comes to objects. Note the snippet below that what resolves to and object type. So know that these are all classified as an object.

    const getDataTypes = () => {
      let arr = []
      let setData = new Set()
      let obj = {}
      
      console.log(`Data types:`, {
       arrType: typeof arr,
       setType: typeof setData,
       objType: typeof obj,
      })
    }
    
    getDataTypes()

    Now we are past that

    Let’s talk about uniqueElements. Your uniqueElements object is acting as a reference here to detect your duplicates in your array.

    When you use [element] = 'foo' this is assigning the object key or property dynamically rather than explicitly entering the property name like

    uniqueElements.color = element 
    

    And since we can’t assign numbers to an object key name this is what calls for the need to use [] to create a new key-value entry into our uniqueElements object. All object properties are unique so if a key with the same name gets assigned again. It will become that latest value assigned.

    uniqueElements.[element] = element
    

    Time for an example

    let exampleArray = [1, 2, 3, 4]
    
    const createDynamicObject = (arr) => {
      // Create a new object to reference our array
      let arrObjectRef = {} // To track entries
      let arrOfObjs = []
      
      arr.forEach((number) => {
        // create our object reference from the array and assign it our values
        arrObjectRef[number] = number // Assign key-value key = '1' value = 1 output => { '1': 1 }
        
        arrOfObjs.push(arrObjectRef)
      })
      
      console.log('Array of objects created:', arrOfObjs)
      console.log('Object ref created:', arrObjectRef)
      
      return arrObjectRef
    }
    
    const createStaticObject = (arr) => {
      // Create a new object to reference our array
      let arrObjectRef = {numberKey: ''} // To track entries
      let arrOfObjs = []
      
      arr.forEach((number) => {
        // create our object reference from the array and assign it our values
        arrObjectRef.numberKey = number // Assign key-value key = '1' value = 1 output => { '1': 1 }
        
        arrOfObjs.push(arrObjectRef)
      })
      
      console.log('Static - Array of objects created:', arrOfObjs)
      console.log('Static - Object ref created:', arrObjectRef)
      
      return arrObjectRef
    }
    
    createDynamicObject(exampleArray) // Outputs entire key value relation setting the number for the key and the value
    createStaticObject(exampleArray) // Outputs { numberKey: 4 } Same key's value gets updated/overwritten

    Conclusion

    I hope this helps! Ideally, would anyone use this as a method to detect dupes? Perhaps not, there are plenty of other ways to do this with new Set(), .reduce(), .find(), .findIndex(), .filter(), and many more. These forms of data declaration are forms of refs for another piece of running code to refer to for a logical reason or condition. Have a blast with the JavaScript world! Its plenty to learn! The large community is here to help! Happy hacking! 😎

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search