0

I have a list of strings, I want to check if the string contains a specific word, and if it does split all the words in the string and add it to an associative array.

   myString = ['RT @Arsenal: Waiting for the international', 'We’re hungry for revenge @_nachomonreal on Saturday\'s match and aiming for a strong finish']

   wordtoFind = ['@Arsenal']       

I want to loop through the wordtoFind and if it is in myString, split up myString into individual words and create an object like

  newWord = {@Arsenal:{RT:1},{Waiting:1},{for:1},{the:1},{international:1}}


  for(z=0; z <wordtoFind.length; z++){
           for ( i = 0 ; i < myString.length; i++) {
             if (myString[i].indexOf(wordtoFind[z].key) > -1){

                 myString[i].split(" ")

             }

I am currently stuck and I am not sure how to continue.

qwerty ayyy
  • 375
  • 2
  • 15

2 Answers2

1

You can't do it. key value objects are not sorted by keys. take a look at Does JavaScript Guarantee Object Property Order

you can turn it into a sorted array.

// Turn to array
var arr = [];
for(var key in mydict) { 
    arr.push({key: key, val: mydict[key]})
}
// Sort
arr.sort(function(a, b) {
    return a.val - b.val;
})
Community
  • 1
  • 1
dcohenb
  • 2,008
  • 1
  • 14
  • 32
1

Use temporary array for sorting your values

var dict = { a: 5, b: 9, z: 21, n: 1, y: 0, g: 3, q: 6 }

var a = Object.keys(dict).map(e => ({ key: e, val: dict[e] }))
    .sort((a, b) => a.val - b.val).slice(0, 5);

var r = {};
a.forEach(e => r[e.key] = e.val);

document.write(JSON.stringify(r));
isvforall
  • 7,860
  • 6
  • 27
  • 46