0

I have a set of input fields with checkboxes where the user can choose an option. Then it's saved in local storage as true if checked and false if not. The localStorage under key "passengers" looks like this:

0: {name: "", child: false, luggage: true}
1: {name: "", child: true, luggage: false}
2: {name: "", child: false, luggage: true}
3: {name: "", child: true, luggage: false}

I want to count occurrences of true and store as a number in a variable

public luggageCounter: number;

I was trying to use

this.luggageCounter = countTrue([this.passengers[i].luggage]], true)
console.log(this.luggageCounter)

and const countTrue = (arr, val) => arr.reduce((a, v) => (v === val ? a +1 : a), 0)

but both of these solutions don't work. I was also thinking about making it easier and toggling the value from HTML by adding code below with [ngClass] and binding it with method in component.ts but also with no success.

<div>Extra luggage: {{ passengers[i].luggage ? 'Yes' : 'No' }}<div>

Any ideas how to make this simple task work? I'm out of ideas :)

1 Answer 1

1

Please try the following solution

const data = [
  { name: "", child: false, luggage: true },
  { name: "", child: true, luggage: false },
  { name: "", child: false, luggage: true },
  { name: "", child: true, luggage: false },
];

const total = data.reduce((previousValue, currentValue) => {
  if (currentValue.luggage) {
    previousValue += 1;
  }

  return previousValue;
}, 0);

console.log(total);

See

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

1 Comment

Thank you! That's exactly what I was looking for! :)

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.