I have to merge two arrays and sort by created value based on comparison. I don't want to use any inbuilt js functions like sort. I tried using while loop but couldn't figure out exact solution. Here is my sample code:
function merge(a, b, n, m)
{
res = [];
i = 0; j = 0; k = 0;
while(i < n && j < m) {
if(a[i]['created'] < b[j]['created']) {
res.push(a[i]);
i++;
} else {
res.push(b[j]);
j++;
}
}
while(i < n) {
res.push(a[i]);
i++;
}
while(j < m) {
res.push(b[j]);
j++;
}
return res;
}
a = [{'title':'title1', 'created':'18'},{'title':'title2', 'created':'16'},{'title':'title3', 'created':'20'}];
b = [{'title':'title4','created':'17'},{'title':'title5','created':'19'}];
n = a.length;
m = b.length;
var endResult = merge(a, b, n, m);
console.log(endResult);
My expected Output should be as follows:
[{'title':'title2', 'created':'16'},{'title':'title4','created':'17'},{'title':'title1', 'created':'18'},{'title':'title5','created':'19'},{'title':'title3', 'created':'20'}];
Please let me know what i missed out here.
Note: I don't want to use in-built Javascript function like sort(). I have to sort values based on specific business logic, which i shall implement after figuring out basic sort.
awith elements of arrayb. You need to compare elements that belong to the same array too.sortroutine is straightforward. There are plenty of examples of BubbleSorts, QuickSorts, TimSorts, MergeSorts, and others online. While you could easily write your own version of one of these, it would very likely offer nothing over writing your code with a custom comparator supplied to the built-insort. You can even reuse that comparator in amergestep. A customsortonly makes sense if you're doing it as a learning exercise.