简体   繁体   中英

Need to iterate through an array to get specific key: value pairs to add to empty object

For this problem, the function accepts an array of strings and returns an object. Keys are supposed to be the number of characters in a string and the value is supposed to be how many time a string with that amount of characters occurred.

I thought I was going somewhere and then I got stuck. I'd appreciate some help on this, I've tried googling it a million different ways but no luck. Thank you!

The result is supposed to look like: characterCount(['apple', 'berry', 'cherry']) // {5:2, 6:1}

function characterCount(arr){

  var newObj = {};
  var valueMax = 0;
  var  currentValue = 0;

  for(var i=0; i < arr.length; i++){
  var key = arr[i].length;
  for(var z=0; z < arr.length; z++){
    if (arr[z].length === arr[i].length){
      currentValue ++;
      if (currentValue > valueMax){
        valueMax = currentValue;
      }
    }
  }
  newObj.key = "valueMax";
}
return newObj;
}

Look at the Array.prototype.reduce function. This allows you to take an array, iterate over each value, and return a new, reduced value.

 function characterCount(arr) { return arr.reduce((counts, str) => ({...counts, [str.length]: (counts[str.length] || 0) + 1 }), {}); } const counts = characterCount(['apple', 'berry', 'cheery']); console.log(counts);

Alternatively, you could use Object.assign instead of spreading the accumulator object.

 function characterCount(arr) { return arr.reduce((counts, str) => Object.assign(counts, { [str.length]: (counts[str.length] || 0) + 1 }), {}); } const counts = characterCount(['apple', 'berry', 'cheery']); console.log(counts);

You could just reduce the array to accomplish the output

 function characterCount( array ) { return array.reduce( (agg, cur) => { // get the length of the current item const len = cur.length; // increase the value of the key index with one (if none exist, start with 0) agg[len] = (agg[len] || 0) + 1; // return the next value for the iteration return agg; }, {}); } console.log( characterCount(['apple', 'berry', 'cherry']) );

Using reduce is arguably better but here is a more straightforward approach.

 function characterCount(arr) { const countByLength = {}; for (let item of arr) { countByLength[item.length] = (countByLength[item.length] || 0) + 1; } return countByLength; } console.log(characterCount(['apple', 'berry', 'cherry']));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM