0

I got this sample data.

"array" : [
    {"Id" : "1", "preferred" : false}, 
    {"Id" : "1", "preferred" : true }, 
    {"Id" : "2", "preferred" : false}, 
    {"Id" : "2", "preferred" : false},]

And i would like to get out of it something like this.

"array2":[{"Id": 1, numOfTrue: 1, numOfFalse: 1},{"Id": 2, numOfTrue: 0, numOfFalse: 2}]

What i got so far is a way how to get unique id form initial array.

const unique = [...new Set(array.map(item => Id))];

Next step would be some forEach over array and comparing Id values and setting some counters for that boolean value. So before i dive into forEach solution i would like to ask if there is another way with using .filter() and .reduce() methods.

2
  • The data you want to get out doesn't exist in the array you want to get it out of. Commented Dec 9, 2018 at 17:44
  • @ScottMarcus - I think he means that the numOfTrue is the number of records with that id that have a preferred: true value and similarly for numOfFalse. Commented Dec 9, 2018 at 17:45

1 Answer 1

1

You can use reduce() to build a grouping object keyed to Id. Each time you see that Id again increment the value at the appropriate key. In the end your array will be the Object.values() of the object:

let array = [
    {"Id" : "1", "preferred" : false}, 
    {"Id" : "1", "preferred" : true }, 
    {"Id" : "2", "preferred" : false}, 
    {"Id" : "2", "preferred" : false}
]

let counts = array.reduce((counts, {Id, preferred}) => {
    // If you haven't seen this Id yet, make a new entry
    if (!counts[Id]) counts[Id] = {Id, numOfTrue: 0, numOfFalse: 0}

    // increment the appropriate value:
    if (preferred) counts[Id].numOfTrue++
    else counts[Id].numOfFalse++
    return counts
}, {})

// get the values array of the object:
console.log(Object.values(counts))

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

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.