Nguyen Hoang
Nguyen Hoang

Reputation: 548

Filter objects by minimum value attributes in javascript

I have an array of objects like below:

[
    {
        "id": 100,
        "Name": "T1",
        "amt": 15,
    },
    {
        "id": 102,
        "Name": "T3",
        "amt": 15,
    },
    {
        "id": 100,
        "Name": "T1",
        "amt": 20,
    },
    {
        "id": 105,
        "Name": "T6",
        "amt": 15,
    }
]

I want to filter the objects in the array by the minimum of amt. There are two objects with id's 100 but different amt (15 and 20). I want to filter the minimum value which is 15. The output should be:

[
    {
        "id": 100,
        "Name": "T1",
        "amt": 15,
    },
    {
        "id": 102,
        "Name": "T3",
        "amt": 15,
    },
    {
        "id": 105,
        "Name": "T6",
        "amt": 15,
    }
]

I followed this post but does not fit with my problem. Is there any simpler way of doing this, either pure JavaScript or lodash?

Upvotes: 4

Views: 1076

Answers (3)

EugenSunic
EugenSunic

Reputation: 13703

Use the standard algorithm for finding min value and apply the approach to the reduce function. When you find the min or the equal value to the min, add the current object to the array.

const arr = [{
    "id": 100,
    "Name": "T1",
    "amt": 15,
  },
  {
    "id": 102,
    "Name": "T3",
    "amt": 15,
  },
  {
    "id": 100,
    "Name": "T1",
    "amt": 20,
  },
  {
    "id": 105,
    "Name": "T6",
    "amt": 15,
  }
]
const minArr = arr.reduce((acc, curr) => curr.amt <= acc.min ? {
  ...acc,
  min: curr.amt,
  arr: [...acc.arr, curr]
} : acc, {
  min: Infinity,
  arr: []
}).arr
console.log(minArr);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386680

You could group by id and take from every group the object with min value of amt.

var data = [{ id: 100, Name: "T1", amt: 15 }, { id: 102, Name: "T3", amt: 15 }, { id: 100, Name: "T1", amt: 20 }, { id: 105, Name: "T6", amt: 15 }],
    result = _(data)
        .groupBy('id')
        .map(group => _.minBy(group, 'amt'))
        .value();

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

Upvotes: 3

Kenzoid
Kenzoid

Reputation: 294

You can do this using a for loop like so:

var minimum = 5;

for(var i = 0; i < yourArray; i++) {
    if(yourArray[i].amt < minimum) {
        console.log("The " + i + " item in the array's amount is less than the minimum: " + minimum);
    }
}

Or you can use Array.filter:

var minimum = 5;

function isBigEnough(value) {
  return value >= minimum
}

someArray.filter(isBigEnough)

Upvotes: -3

Related Questions