arty
arty

Reputation: 669

Javascript - Adding multiple values to keys

I am trying to find the places of each letter in a sentence by using "dictionaries". The problem is I want to find all the places that each letter is and not only the last one. I am very new to JavaScript and couldn't figure out the way to do it.

function letters(stringArgument) {
stringArgument = stringArgument.replace(/ /g,'');
var dict = {};
for (var i=0; i < stringArgument.length; i++ )

    if (!stringArgument[i] in dict){
       dict[stringArgument[i]] = [];
    }else{
       dict[stringArgument[i]] = [i+1]
    }
return dict
}
var a = letters('Lost time is never found again.');
console.log(a);

naturally gives this output:

{   L: [ 1 ],   o: [ 17 ],   s: [ 10 ],   t: [ 5 ]...

but it should give this:

{   L: [ 1 ],   o: [ 2, 17 ],   s: [ 3, 10 ],   t: [ 4, 5 ]...

Also each letter is saved to the dictionary at the same order they appear in the sentence, how can I order the letters alphabetically?

Upvotes: 2

Views: 2834

Answers (5)

Mister Jojo
Mister Jojo

Reputation: 22386

for the first part you can also do that:

let  sentence = 'Lost time is never found again.'

let tabLetters = [...sentence.replace(/ /g,'')].reduce((a,c,i)=>
  {
  if (!a[c]) a[c] = [i+1]
  else       a[c].push(i+1)
  return a
  },{})

document.write(JSON.stringify(tabLetters))

Upvotes: 1

shashi srinath
shashi srinath

Reputation: 88

you are assigning a new array at each iteration

dict[stringArgument[i]] = [i+1]

what you need to do is push the new position to existing array.

dict[stringArgument[i]].push(i+1)

also, remove the else block

function letters(stringArgument) {
    stringArgument = stringArgument.toLowerCase().replace(/ /g,'');
    var dict = {};
    for (var i=0; i < stringArgument.length; i++ ){
        if (!dict.hasOwnProperty(stringArgument[i])){
           dict[stringArgument[i]] = [];
        }
        dict[stringArgument[i]].push(i+1);
    }

    //sorting
    var letters = Object.keys(dict); //returns a array

    letters.sort();

    var sortedDic = {};
    for(var i in letters) {
       sortedDic[letters[i]] = dict[letters[i]];
    }

    return sortedDic;
    }
    var a = letters('Lost time is never found again.');
    console.log(a);

Upvotes: 1

Aadil Mehraj
Aadil Mehraj

Reputation: 2614

What you need is a function that gets the positions of a character in a given string.

Try this:

function findAllPositions(char, content) {
    var result = [];
    let index = content.indexOf(char);

    while(index !== -1) {
        result.push(index);
        index = content.indexOf(char, index + 1);
    }

    return result;

}

findAllPositions('o', 'Lost time is never found again.'); // Result =  [1, 20]

Using this we can update the letter function as follows:

function letters(stringArgument) {
  stringArgument = stringArgument.replace(/ /g, '');
  var dict = {};
  for (const char of stringArgument) {
    dict[char] = findAllPositions(char, stringArgument)
  }
  return dict;
}

letters('is again.')
/*
{
    "i": [0, 5],
    "s": [1],
    "a": [2, 4],
    "g": [3],
    "n": [6],
    ".": [7]
}
*/

Upvotes: 2

Kingson
Kingson

Reputation: 119

First, for any item, if it is not in an empty array:

var notInDict = !(stringArgument[i] in dict);

If not in dict, then initialize an empty array and push the item in it using

dict[stringArgument[i]].push(i + 1);

Try this.

function letters(stringArgument) {
  stringArgument = stringArgument.replace(/ /g, "");
  var dict = {};
  for (var i = 0; i < stringArgument.length; i++) {
    var notInDict = !(stringArgument[i] in dict);
    if (notInDict) {
      dict[stringArgument[i]] = [];
    }
    dict[stringArgument[i]].push(i + 1);

  }
  return dict;
}
var a = letters("Lost time is never found again.");
console.log(a);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386836

You need to have

  • parantheses for the check

    if (!(stringArgument[i] in dict)) {
    
  • create an array if the above is true

  • push the postion to the array

For getting a sorted output, you could take the entries of the object, apply a sorting by taking the key and show the result in order.

Object have an insertation oder for not positive 32 bit numbers (like indixes) or symbols. The index like numbers are sorted by value and appears first in the object.

function letters(stringArgument) {
  stringArgument = stringArgument.replace(/ /g, '');
  var dict = {};
  for (var i = 0; i < stringArgument.length; i++) {
    if (!(stringArgument[i] in dict)) {
      dict[stringArgument[i]] = [];
    }
    dict[stringArgument[i]].push(i + 1);
  }
  return dict;
}

var a = letters('Lost time is never found again.');

Object
    .entries(a)
    .sort(([a], [b]) => a.localeCompare(b))
    .forEach(([key, positions]) => console.log(key, ...positions));

console.log(a);

Upvotes: 1

Related Questions