0

I have an array of objects with the following structure:

[ { type: 'A', rank: 10 }, { type: 'B', rank: 10 }, { type: 'A', rank: 16 }, { type: 'B', rank: 16 } ]

I'd like to keep 1 object per object.type, that one where the object.rank is the biggest, so my expected output in this case is:

[ { type: 'A', rank: 16 }, { type: 'B', rank: 16 } ]

My code is:

conditions = conditions.filter((cond, index, self) => self.findIndex((t) => {return t.type === cond.type && t.rank < cond.rank; }) === index);

This code removes all of the objects. When I don't use the

t.rank < cond.rank

then it works but there is no guarantee it will gives back the biggest rank.

Thank you in advance, of course I don't insist to an ES6 solution.

2 Answers 2

2

You can use a combination of Array.reduce and Array.findIndex to get the desired results.

const conditions = [{
  type: 'A',
  rank: 10
}, {
  type: 'B',
  rank: 10
}, {
  type: 'A',
  rank: 16
}, {
  type: 'B',
  rank: 16
}];

const transformed = conditions.reduce((result, item) => {
  const itemIdx = result.findIndex(condition => condition.type === item.type && condition.rank < item.rank);

  if (itemIdx !== -1) {
    result.splice(itemIdx, 1, item);
  } else {
    result.push(item);
  }

  return result;
}, []);

console.log(transformed);

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

2 Comments

Thank you for the answer. I made my own based on your answer. The only problem was it is not worked with other inputs (when the order is different). I added an extra condition into the else case: if (itemIdx !== -1) { result.splice(itemIdx, 1, item); } else { var typeExists = result.findIndex(condition => condition.type === item.type); if (typeExists === -1) { result.push(item); } }
@Paxi -- Please include the additional requirements in your question. This solution was as per your current requirements.
1

I made up my own solution using simple javascript functions.

  var conditions = [{ type: 'A', rank: 10 }, { type: 'B', rank: 10 }, { type: 'A', rank: 16 }, { type: 'B', rank: 16 }];

    function check(type, rank) {    
           for (var j = 0; j < conditions.length; j++) {   
            if (conditions[j].type == type) {   
                if (conditions[j].rank > rank) {  
                    return 1;  
                }  
            }  
        }  
        return 0;  
    } 

    for (var i = 0; i < conditions.length; i++) {
        if (check(conditions[i].type, conditions[i].rank)) {
            conditions.splice(i, 1);
            i = i - 1;
        }
    }
    console.log(conditions);

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.