0

I am at hour 14 of learning JavaScript, and doing some challenges.

The aim of this code is to find out how often a numbr occurs in the input.

The output is correct, if it occurs once it needs to be 0. (Don't ask me why this is?! They want it like that and might have a reason. )

I don't think the solution is the most elegant. You can surely help me out here and tell me how to write it better. I had to add " " to the first and last position of the input and then - to convert it into an array - remove them again or it would create a new empty item to the array ( i think). Is there a better way to accomplish this?

var input =" 12 34 56 78 12 34 1 87 12 "
var digits= input.trim();
    digits= digits.split(" ");
var arrayLength= digits.length;
var output ="";

for(var n=0; n<arrayLength; ++n){
    var outputD =-1;  
    var inputLocal = input;

    while (inputLocal.search(" " + digits[n] +" ") >= 0) {
        inputLocal = inputLocal.replace(" " +digits[n]+" ", ""); 
        ++outputD;
    } 
output += " " + outputD;
console.log(output);
};

2 Answers 2

1

You can use a object as a map for counting, then use map to create the new array and then use join, like:

var input = ' 12 34 56 78 12 34 1 87 12 '
    arr = input.trim().split(' '),
    count = {}, result;

arr.forEach(function(item){
  if (typeof count[item] !== 'undefined') {
    count[item]++;
  } else {
    count[item] = 0; 
  }
});

result = arr.map(function(item){
  return count[item];
});

console.log(result.join(' '));
Sign up to request clarification or add additional context in comments.

Comments

1
console.log(
  " 12 34 56 78 12 34 1 87 12 "

  .trim()
  .split(/\s+/)

  .reduce(function (collector, item) {

    if (item in collector) {
      ++collector[item]
    } else {
      collector[item] = 0; // 1
    }
    return collector;

  }, {})
);

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.