Sqveeze
Sqveeze

Reputation: 73

Get element from array that is bigger than num, plus the next index

I have an object like this:

const obj = {
  1: 10,
  2: 20,
  3: 30,
  4: 40,
  5: 50,
};

And i have a number for example: 25

Now i want to iterate over the obj with Object.entires(obj), and i need the result like: 25 is bigger than the second element value: 20. So the return value should be:

{ 2: 20 } <- this one is working flawless, but how can i get the result like:

{
  current: {
    2: 20
  },
  next: {
    3: 30
  }
}

I also need the next value from the obj.

Upvotes: 0

Views: 89

Answers (1)

Leaf the Legend
Leaf the Legend

Reputation: 481

You can first convert your object into an array:

arr = Object.entries(obj);

This will return an array of key value pairs. Then, loop over your array using forEach:

n = 25;
const obj = {
  1: 10,
  2: 20,
  3: 30,
  4: 40,
  5: 50,
};
arr = Object.entries(obj);
res = {};
arr.forEach((elem,index,array)=>{
if(n>elem[1]){
res.current = {[elem[0]]:elem[1]};
//get index from provided argument
res.next = {[array[index+1][0]]:array[index+1][1]};
}
});
console.log(res);

The advantage of forEach is that it passes an index parameter which you can use to get the next object in the array.

Upvotes: 1

Related Questions