'Stuck between Selected with .JS .filters/.map

So I got this segment of code, whenever someone has the highest selected they are meant to be removed from the query, as you can see from the snippet it works normal, 4 is caught and removed as supposed to.

const result_arr = [
  {selected: 3, absent: 0},
  {selected: 4, absent: 0},
  {selected: 2, absent: 0},
]

const max = Math.max(
  ...result_arr.filter(item => !item.absent).map(item => item.selected)
);
console.log(max);
  
let newArr = result_arr.filter(item => item.selected != max).filter(item => !item.absent);
console.log(newArr);

I'm running into an issue seen in the snippet below. Whenever one of the Selected hit equal numbers, which will most definitely occur, it returns an empty array.

const result_arr = [
  {selected: 4, absent: 0},
  {selected: 4, absent: 0},
  {selected: 4, absent: 0},
]

const max = Math.max(
  ...result_arr.filter(item => !item.absent).map(item => item.selected)
);
console.log(max);
  
let newArr = result_arr.filter(item => item.selected != max).filter(item => !item.absent);
console.log(newArr);

What I want instead is for all 3 to be returned and used, as seen in the snippet below.

const result_arr = [
  {selected: 4, absent: 0},
  {selected: 4, absent: 0},
  {selected: 4, absent: 0},
]

const max = Math.max(
  ...result_arr.filter(item => !item.absent).map(item => item.selected)
);
console.log(max);
  
let newArr = result_arr.filter(item => item.selected == max).filter(item => !item.absent);
console.log(newArr);

I changed != to ==, so I'm wary of how to do this but how do I compile this into one? Will an If else work, I already tried one.



Solution 1:[1]

Your initial code seems too complicated for your requirements.

  1. Get an array of selected values.

  2. Get the max of those values.

  3. If every value in the selected array is max return the whole array, otherwise return the filtered array.

const arr=[{selected:3,absent:0},{selected:4,absent:0},{selected:2,absent:0}];
const arr2=[{selected:4,absent:0},{selected:4,absent:0},{selected:4,absent:0}];
const arr3=[{selected:4,absent:0},{selected:2,absent:0},{selected:4,absent:0}];

function check(arr) {

  const selected = arr.map(obj => obj.selected);

  const max = Math.max(...selected);

  if (selected.every(el => el === max)) {
    return arr;
  }

  return arr.filter(item => item.selected !== max)

}

console.log(check(arr));
console.log(check(arr2));
console.log(check(arr3));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1