Thursday, 9 November 2017

Easiest way to search without using loop

If you have two sets of data and one set is referencing the other set, you will need to do a "double loop" to iterating through the data. But, there is a way to eliminate one loop and shorten the code.

For example, set 1 is the list of employees and set 2 is the list of working shift.

If you are using FOR loop, your codes will look similar to the following:

var employees = [];
employees.push({name: 'Mike', shift_id:'A'});
employees.push({name: 'Micky', shift_id:'B'});
employees.push({name: 'Mini', shift_id:'C'});

var shifts = [];
shifts.push({id: 'A', start_time: '08:00', end_time: '17:00'});
shifts.push({id: 'B', start_time: '09:00', end_time: '18:00'});

var s;

for (var i = 0; i < employees.length; i++) {
    s = null;

    // look for the shift:
    for (var j = 0; j < shifts.length; j++) {
         if (shifts[j].id == employees[i].shift_id) {
            s = shifts[j];
            break;
        }
    }

     if (s != null){
           console.log(employees[i].name, s.start_time);
     } else {
           console.log(employees[i].name, 'Cannot find the shift record');
     }
}

The JavaScript object is a key value collection:

   o = {};
   o['a'] = 'Apple';
   o['b'] = 'Banana';

And you can access the value:

   console.log(o['b']);

Below is the code that uses the key value collection to store the shift information and it will save us from writing one FOR loop.

var employees = [];
employees.push({name: 'Mike', shift_id:'A'});
employees.push({name: 'Micky', shift_id:'B'});
employees.push({name: 'Mini', shift_id:'C'});

var shifts = {};
shifts['A'] = {id: 'A', start_time: '08:00', end_time: '17:00'};
shifts['B'] = {id: 'B', start_time: '09:00', end_time: '18:00'};

var s;

for (var i = 0; i < employees.length; i++) {
    s = null;

    // look for the shift:
    if (shifts.hasOwnProperty(employees[i].shift_id)) {
            s = shifts[employees[i].shift_id];
           console.log(employees[i].name, s.start_time);
     } else {
           console.log(employees[i].name, 'Cannot find the shift record');
     }
}

No comments:

Post a Comment

We are moving

We are moving this blog to our new blog site: https://ciysys.com/blog/nodejs.htm