Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find value in array from key

Tags:

arrays

jquery

I have an array (Dates) of 600 items like this: [{Case: 1, Date: 01012019},{Case: 2, Date: 01022019},{Case: 3, Date: 01032019}

What is the best approach to get the value from the key "Date" based on the key "Case"?

I know I can do a simple loop ($.each())on the array and break out of the loop once i find the key I'm looking for. Another option - as far as I've read at least - is to use the $.map() function.

I will need to lookup the key for 50-100 items on page load, so looping the array (Dates) seems like a lot of work to get me there. Is there a more efficient way? Og talking javescript/Jquery here :)

like image 768
Morten K Avatar asked Nov 23 '25 08:11

Morten K


1 Answers

Transform the array into an object indexed by Case first, and then instead of using a for loop or .find to find the associated object each time, just use object property lookup to find the associated object:

const dates = [{
  Case: 1,
  Date: 01012019
}, {
  Case: 2,
  Date: 01022019
}, {
  Case: 3,
  Date: 01032019
}];

const datesByCase = dates.reduce((a, item) => {
  a[item.Case] = item;
  return a;
}, {});

// now say we want to find objects associated with case 2 and 3:
console.log(datesByCase['2']);
console.log(datesByCase['3']);

For N Cases to find, this has O(N) complexity overall. (Using a for loop for every Case you want to find has O(N^2) complexity overall)

like image 53
CertainPerformance Avatar answered Nov 25 '25 22:11

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!