0

i am making one function that is finding the index of two values that sums up to 9

      var twoSum = function(nums, target) {
          let obj ={};
          const result = [];
          for(let i =0; i< nums.length; i++){
              if(obj[nums[i]]){
                 result.push(obj[nums[i]]);
                 result.push(i);
              }
              let a = target - nums[i]; 
              obj[a] = i;
              console.log(obj)
          }
              console.log(result)

      };

      twoSum([2 ,4 ,7 ,8 ], 9);

//OUTPUT

{ 7: 0 }

{ 5: 1 , 7: 0 }

{ 2: 2 , 5: 1 , 7: 0 }

{ 1: 3 , 2: 2 , 5: 1 , 7: 0 }

here the items are apended to object in some random sort of way. instead they should apeended one after the another why?

Rahul Syal
  • 333
  • 2
  • 5
  • 13
  • An array is an ordered object, if you want to guarantee order, you'd have to make it an array or keep it as an object an add a 'order' node. Objects never promise any sort of order to anything, they only promise the key will exist somewhere within the object - If you see the object appear to be ordered, then it was just a coincidence or something external is ordering it (some browser consoles will do that) – Kyle Aug 30 '19 at 18:34

2 Answers2

0

The keys are being sorted numerically. Check this out:

const obj = {};
obj[3] = 'a';
obj[2] = 'b';
obj[1] = 'c';
console.log(obj);
// { '1': 'c', '2': 'b', '3': 'a' }

Arrays in javascript are just objects with numerical keys. You're sort of creating an array already, just in the worst way possible. As Kyle said, use an array if you want to intuitively maintain the order.

Michael
  • 527
  • 1
  • 6
0

The order of JavaScript properties cannot be guaranteed

This is a common missconcept, the iteration order for objects follows a certain set of rules since ES2015, but it doesn't follow the insertion order. The iteration order is a combination of the insertion order for strings keys, and ascending order for number and number-like keys:

// key order: 1, foo, bar
const obj = { "foo": "foo", "1": "1", "bar": "bar" }

Check this answer for more details about the rules

Dupocas
  • 15,944
  • 5
  • 23
  • 43