1

This is my function in foreach loop for creating object which has property and value as word and its count, but i want to convert it in map according to es6

function harmlessRamsonNote(noteText,magazineText)
{
  var noteArr = noteText.split(' ');
  var magazineArr = magazineText.split(' ');
  var magazineObj = {};

  magazineArr.forEach(word => {
    if(!magazineObj[word])
    {
      magazineObj[word] = 0;
    }
    magazineObj[word]++;
  });

  console.log(magazineObj);
};

2 Answers 2

2
magazineArr.map((word, index, array) => {
   !magazineObj[word] ? magazineObj[word] = 0 : magazineObj[word]++;
})
Sign up to request clarification or add additional context in comments.

Comments

2

map will return an new item for each item. Instead you can use reduce.

const magazineObj = magazineArr.reduce((acc,word) => {
   acc[word] = (acc[word] || -1) + 1;
}, {});

4 Comments

it gives error as magazineObj not defined in this line magazineObj[word] = (magazineObj[word] || -1) + 1;
It still give error as acc[word] = (acc[word] || -1) + 1; ^ TypeError: Cannot read property 'is' of undefined I think its because in first loop value of acc is undefined though i am not sure of this anyways i really appreciate your help and response though
I have not worked with is, maybe it is your error?
When i call the function with this harmlessRamsonNote('','this is the ramson the the text'); it gives that error, i.e gives error in second word of passed string

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.