最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

dictionary - Javascript - Adding multiple values to keys - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Apr 19, 2020 at 13:50 artyarty 6691 gold badge7 silver badges12 bronze badges 1
  • 1 Property names in objects cannot be ordered other than in the way the runtime naturally behaves. You can extract the property names yourself however and sort them for presentation. – Pointy Commented Apr 19, 2020 at 13:52
Add a ment  | 

5 Answers 5

Reset to default 2

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]
}
*/

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);

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);

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);

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))

发布评论

评论列表(0)

  1. 暂无评论