0

My question is it possible to change and array into an object?

The following code counts the number of occurrences of each word in an array.

// function for getting the frequency of each word within a string
function getFreqword(){
  var string = tweettxt.toString(), // turn the array into a string
      changedString = string.replace(/,/g, " "), // remove the array elements 
      split = changedString.split(" "), // split the string 
      words = []; 

  for (var i=0; i<split.length; i++){
    if(words[split[i]]===undefined){
      words[split[i]]=1;
    } else {
      words[split[i]]++;
    }
  }
  return words;
}

Is it possible to change it so that instead of returning an array like this:

[ Not: 1,
  long: 1,
  left: 2,
  grab: 1,
  an: 4,
  Easter: 5,
  bargain: 1,]

instead it returns an object like this? { word: 'Not' num: 1 } etc.

8
  • 1
    You can assign object properties with bracket notation. var obj = {}; then dot notation add a property obj.prop1 = 2; or bracket notation like obj["prop2"] = 2; the handy thing is that bracket notation can use a string thus var propName = "prop3" then obj[propName] = 2; giving obj.prop3 === 2 as true. Commented Mar 29, 2016 at 16:41
  • I suppose what you really want is an array of objects : [ { word: 'Not', num: 1 }, { word: 'long', num: 1 }, ... ] rather than a single object. Commented Mar 29, 2016 at 16:45
  • @Andy tweetxt is and array that is then turned into a string that can be sorted Commented Mar 29, 2016 at 16:48
  • @Arnauld If I can sort that array by the num element of the object then yes. Commented Mar 29, 2016 at 16:49
  • @cockmagic, can you show the initial tweetxt value ? Commented Mar 29, 2016 at 16:56

1 Answer 1

2

You can use Object.key() and Array#map() for converting an object into an array of objects.

var obj = { Not: 1, long: 1, left: 2, grab: 1, an: 4, Easter: 5, bargain: 1 },
    array = Object.keys(obj).map(function (k) { return { word: k, num: obj[k] }; });

document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');

// edit sorting

array.sort(function (a, b) { return a.num - b.num; });
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.