javascript - Adding an element to an object in a for loop -


I want to populate an object with long encoding of a string. Using the array would be simple, but I'm not sure what to do for an object.

  function addto (string) {var string = string.split ("") .sort (); Var cnt = 1; Var obj = {}; For (i = 0; i   

Now clearly I can not use a method here (push). But I can not set the object name to the string that I like:

  obj.string [i] = cnt;   

Hope that was what I initially had to do. Is there a proper way to do that my output will be given (for example):

  {"a": 1, "b": 2, "c": 3}    

For each letter in the string, you type obj For once the counter is a push in the right direction here.

  var obj = {}; (I = 0; i & lt; string.length; i ++) {// If the character has not been seen yet, set your counter of 0. [ORG [string] [I]] = OBJ [string [i]] || 0; // Count that character once obj [string [i]] ++; }   

Note that from this direction, you do not need to sort the array in advance.

Here is another option if you are doing it as a coursework, do not use it. But as a mental exercise, I leave the solution:

  var str = "abbccccddeeeeefgh" var matches = str.match (/ (.) \ 1 * / g); // matches = ["A", "BB", "CCCC", "DD", "Eee ee", "F", "G", "H"] Works = {}; To calculate (i matches) [matches [ii] [0]] = matches [ii] Length; // calculation = object {a: 1, b: 2, c: 4, d: 2, e: 5, f: 1, g: 1, h: 1}    

Comments

Popular posts from this blog

Java - Error: no suitable method found for add(int, java.lang.String) -

java - JPA TypedQuery: Parameter value element did not match expected type -

c++ - static template member variable has internal linkage but is not defined -