skip to Main Content

For the array of object arrobj, if the id id matches with input id idparam

how to get the immediate first larger value cost object using javascript

Tried

var result = arrobj.find((e, index) => e.id === idparam && arrobj.indexOf(index));

example 1

var idparam1 = 22; 
var arrobj1 = [
  {id:11, cost: 4},
  {id:22, cost: 2}
  {id:33, cost: 1},
  {id:44, cost: 5} 
]

Expected output:

{id:11, cost: 4}

example 2

var idparam2 = 33; 
var arrobj2 = [
  {id:11, cost: 4},
  {id:22, cost: 2},
  {id:33, cost: 1},
  {id:44, cost: 5},
  {id:54, cost: 6} 
]

Expected output:

{id:22, cost: 2}

2

Answers


  1. You can try sorting

    function nextLarger(arr, id) {
      const sorted = [...arr].sort((a, b) => a.cost - b.cost);
      const index = sorted.findIndex((item) => item.id === id);
      return sorted[index + 1];
    }
    
    console.log(
      nextLarger(
        [
          { id: 11, cost: 4 },
          { id: 22, cost: 2 },
          { id: 33, cost: 1 },
          { id: 44, cost: 5 },
        ],
        22
      )
    );
    
    console.log(
      nextLarger(
        [
          { id: 11, cost: 4 },
          { id: 22, cost: 2 },
          { id: 33, cost: 1 },
          { id: 44, cost: 5 },
          { id: 44, cost: 6 },
        ],
        11
      )
    );

    Same without sorting

    function nextLarger(arr, id) {
      const cost = arr.find((item) => item.id === id).cost;
      let larger = Infinity
      let best = undefined
      for (const item of arr) {
        if (item.cost > cost && item.cost < larger) {
          larger = item.cost
          best = item
        }
      }
      return best;
    }
    
    console.log(
      nextLarger(
        [
          { id: 11, cost: 4 },
          { id: 22, cost: 2 },
          { id: 33, cost: 1 },
          { id: 44, cost: 5 },
        ],
        22
      )
    );
    
    console.log(
      nextLarger(
        [
          { id: 11, cost: 4 },
          { id: 22, cost: 2 },
          { id: 33, cost: 1 },
          { id: 44, cost: 5 },
          { id: 44, cost: 6 },
        ],
        11
      )
    );
    Login or Signup to reply.
  2. You could simplify this into a traditional for-loop; and return the previous, if larger.

    const findPrevLargest = (arr, id) => {
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].id === id) {
          return (i > 0 && arr[i - 1].cost > arr[i].cost)
            ? arr[i - 1]
            : arr[i];
        }
      }
      return null;
    };
    
    console.log(findPrevLargest([
      { id: 11, cost: 4 },
      { id: 22, cost: 2 },
      { id: 33, cost: 1 },
      { id: 44, cost: 5 } 
    ], 22)); // { id: 11, cost: 4 }
    
    console.log(findPrevLargest([
      { id: 11, cost: 4 },
      { id: 22, cost: 2 },
      { id: 33, cost: 1 },
      { id: 44, cost: 5 },
      { id: 44, cost: 6 } 
    ], 33)); // { id: 22, cost: 2 }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search