1

I have the following object:

{
  apple: 0,
  banana: 0,
  cherry: 0,
  date: 0,

and so on...
}

And an array of strings that are words from a cookery book.

[0] => "the"
[1] => "apple"
[2] => "and"
[3] => "cherry"

and so on...

I would like to iterate over the array of strings and add +1 every time the above keys are mentioned as a string? I've been trying to use object.keys however have been unable to get it working?

This is in node.js.

3 Answers 3

1

You can do something nice and simple like this, which will increment absolutely all keys from the array of strings:

let ingredients = {
  apple: 0,
  banana: 0,
  cherry: 0,
  date: 0,
  // and more...
}

let arr = ["the","apple","and","cherry"]

// loop through array, incrementing keys found
arr.forEach((ingredient) => {
  if (ingredients[ingredient]) ingredients[ingredient] += 1;
  else ingredients[ingredient] = 1
})

console.log(ingredients)

However, if you want to only increment keys in the ingredients object that you set, you can do this:

let ingredients = {
  apple: 0,
  banana: 0,
  cherry: 0,
  date: 0,
  // and more...
}

let arr = ["the","apple","and","cherry"]

// loop through array, incrementing keys found
arr.forEach((ingredient) => {
  if (ingredients[ingredient] !== undefined)
    ingredients[ingredient] += 1;
})

console.log(ingredients)

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

1 Comment

The ingredients object and the array of words from the book are both in their own respective files within a function each. I have them logging to the console currently, how can I include them within what you have entered above. Is it as easy as making a new file using module exports and then assigning their function let ingredients() = ingredients?
0

You can simplify it using reduce.

const words = ["the", "apple", "and", "cherry"];

let conts = {
  apple: 0,
  banana: 0,
  cherry: 0,
  date: 0,
};
const result = words.reduce((map, word) => {
  if (typeof map[word] !== "undefined") map[word] += 1;
  return map;
}, conts);
console.log(result);

Comments

0

Another way to handle it using array filter and some:

var fruits = {
  apple: 0,
  banana: 0,
  cherry: 0,
  date: 0,
};

const words = ["the", "apple", "and", "cherry"];

var filtered = words.filter(word => Object.keys(fruits).includes(word));
filtered.forEach(fruit => fruits[fruit] += 1);

// fruits
// {apple: 1, banana: 0, cherry: 1, date: 0}
console.log(fruits);

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.