Javascript - Sorting array with objects based on objects value - javascript

So I am trying to sort my array with objects based on an objects value..
var mostCheapHistory [ { lowestTitle: title goes here, lowestPrice: 100 }, another obj, another, another } ]
And I want to sort them based on their price, so I came up with this:
var historyObj = mostCheapHistory[0];
for(var y in mostCheapHistory){
nextObj = mostCheapHistory[y];
console.log('Is '+ historyObj.lowestPrice + ' more as ' + nextObj.lowestPrice + ' ?');
console.log(historyObj.lowestPrice > nextObj.lowestPrice);
console.log('-----')
}
And this is the output...
Is 124.98 more as 124.98 ?
false
-----
Is 124.98 more as 18.59 ?
false
-----
Is 124.98 more as 25.9 ?
false
-----
Is 124.98 more as 26.99 ?
false
-----
Is 124.98 more as 34.76 ?
false
-----
What the hell is going on? It's obvious that 124.98 is more as 34.76 and yet it gives false?
The array is made using this code:
for(var x=0; x < items.length; x++){
var title = items[x].title[0];
var price = items[x].sellingStatus[0].currentPrice[0].__value__;
var item =
{
lowestPrice : price,
lowestTitle : title
}
if(x === 0){
mostCheapHistory.push(item);
}
else{
for(var y=0; y < mostCheapHistory.length; y++){
if(mostCheapHistory[y].lowestPrice > price ){
if(mostCheapHistory.length < 5){
mostCheapHistory.push(item);
break;
}
else{
mostCheapHistory[y] = item;
break;
}
}
}
}
}

Use the predefined sort function :
mostCheapHistory.sort(function(a,b){
return a.lowestPrice - b.lowestPrice;
}
+ Your code might be pushing strings rather than numbers, which explains why 124.98 > 34.76 => true but '124.98' > '34.76' => false, since the string '34.76' is greater than '124.98' in string comparison.
Use parseFloat() for the prices then check again.

It looks like, you are comparing strings instead of numerical values. If you say (in comments), that the sorting function
array.sort((a, b) => a.lowestPrice - b.lowestPrice);
solves your problem, then while this sort callback uses an implicit casting to number with the minus - operator.
The result is a sorted array with values as string.

You can sort these based on price using Array.prototype.sort() (See MDN documentation)
e.g.
var data = [
{
title: "title1",
value: 123
},
{
title: "title2",
value: 324
},
{
title: "title3",
value: 142
}];
var sorted = data.sort(function(a, b) {
return a.value > b.value;
});

I think the type of lowestPrice is string not float, use parseFloat(historyObj.lowestPrice) to compare the two values

Related

Translate aggregation operation in MongoDB to MapReduce

I've been trying to translate this query into MapReduce for a few days. Specifically, I need to figure out how many different cars have driven "N" kilometers.
Query:
db.adsb.group({
"key": {
"KM": true
},
"initial": {
"countCar": 0
},
"reduce": function(obj, prev) {
if (obj.Matricula != null) if (obj.Matricula instanceof Array) prev.countCar += obj.Matricula.length;
else prev.countCar++;
},
"cond": {
"KM": {
"$gt": 10000,
"$lt": 45000
}
}
});
Each document in Mongo has this form:
{
"_id" : ObjectId("5a8843e7d79a740f272ccc0a"),
"KM" : 45782,
"Matricula" : "3687KTS",
}
I'm trying to get something like:
/* 0 */
{
“KM” : 45000,
“total” : 634
}
/* 1 */
{
“KM” : 46000,
“total” : 784
}
My code is below, and it compiles but does not give me the expected results.
In particular, every time I enter 'reduce' it seems to reset all the values to 0, which prevents me from accumulating the registrations.
One of my problems is that when handling large amounts of information, the function must iterate several times ' reduce'.
I also don't know if it could be done that way, or I would need to return a list of car plates and their counter together in 'reduce'; and then in finalize add it all up.
// Map function
var m = function() {
if (this.KM > 10000 && this.KM < 45000) { // So that i can get KM grouped together by thousands (10000, 20000, 30000...)
var fl = Math.round(this.KM / 1000) * 1000;
var car = this.Matricula
emit (fl, car);
//print("map KM=" + fl + " Matricula= " + car);
}
};
// Reduce function
var r = function(key, values) {
var ya_incluido = false;
var cars_totales = 0;
var lista_car = new Array();
//print( key + " ---- " + values);
for (var i=0; i < values.length;i++)
{
for (var j=0; j < lista_car.length;j++)
{
if(values[i] == lista_car[j]) { //If it is already included, don't aggregate it
ya_incluido = true;
}
} if (ya_incluido != true) { //If it is not included, add it to lista_av list.
lista_car.push(values[i]);
} ya_incluido = false;
}
cars_totales = lista_av.length; //The number of distinct cars is equal to the lenght of the list we created
return cars_totales;
};
// Finalize function
var f = function(key,value) {
// Sum up the results?
}
db.runCommand( {
mapReduce: "dealer",
map: m,
reduce: r,
finalize: f,
out: {replace : "result"}
} );
I found the answer and a really good explanation here: https://stackoverflow.com/a/27532153/13474284
I found the answer and a really good explanation here: https://stackoverflow.com/a/27532153/13474284
I couldn't find a way to return in 'reduce' the same thing that came from ' map' . And since it was run several times, it only got the results of the last iteration. The way it appears in the link, the problem is solved without any difficulty.

Javascript: Find out of sequence dates

Consider this nested array of dates and names:
var fDates = [
['2015-02-03', 'name1'],
['2015-02-04', 'nameg'],
['2015-02-04', 'name5'],
['2015-02-05', 'nameh'],
['1929-03-12', 'name4'],
['2023-07-01', 'name7'],
['2015-02-07', 'name0'],
['2015-02-08', 'nameh'],
['2015-02-15', 'namex'],
['2015-02-09', 'namew'],
['1980-12-23', 'name2'],
['2015-02-12', 'namen'],
['2015-02-13', 'named'],
]
How can I identify those dates that are out of sequence. I don't care if dates repeat, or skip, I just need the ones out of order. Ie, I should get back:
results = [
['1929-03-12', 'name4'],
['2023-07-01', 'name7'],
['2015-02-15', 'namex'],
['1980-12-23', 'name2'],
]
('Namex' is less obvious, but it's not in the general order of the list.)
This appears to be a variation on the Longest Increase Subsequence (LIS) problem, with the caveat that there may be repeated dates in the sequence but shouldn't ever step backward.
Use case: I have sorted and dated records and need to find the ones where the dates are "suspicious" -- perhaps input error -- to flag for checking.
NB1: I am using straight Javascript and NOT a framework. (I am in node, but am looking for a package-free solution so I can understand what's going on...)
Here's an adaptation of Rosetta Code LIS to take a custom getElement and compare functions. We can refine the comparison and element-get functions based on your specific needs.
function f(arr, getElement, compare){
function findIndex(input){
var len = input.length;
var maxSeqEndingHere = new Array(len).fill(1)
for(var i=0; i<len; i++)
for(var j=i-1;j>=0;j--)
if(compare(getElement(input, i), getElement(input, j)) && maxSeqEndingHere[j] >= maxSeqEndingHere[i])
maxSeqEndingHere[i] = maxSeqEndingHere[j]+1;
return maxSeqEndingHere;
}
function findSequence(input, result){
var maxValue = Math.max.apply(null, result);
var maxIndex = result.indexOf(Math.max.apply(Math, result));
var output = new Set();
output.add(maxIndex);
for(var i = maxIndex ; i >= 0; i--){
if(maxValue==0)break;
if(compare(getElement(input, maxIndex), getElement(input, i)) && result[i] == maxValue-1){
output.add(i);
maxValue--;
}
}
return output;
}
var result = findIndex(arr);
var final = findSequence(arr, result)
return arr.filter((e, i) => !final.has(i));
}
var fDates = [
['2015-02-03', 'name1'],
['2015-02-04', 'nameg'],
['2015-02-04', 'name5'],
['2015-02-05', 'nameh'],
['1929-03-12', 'name4'],
['2023-07-01', 'name7'],
['2015-02-07', 'name0'],
['2015-02-08', 'nameh'],
['2015-02-15', 'namex'],
['2015-02-09', 'namew'],
['1980-12-23', 'name2'],
['2015-02-12', 'namen'],
['2015-02-13', 'named'],
];
console.log(f(fDates, (arr, i) => arr[i][0], (a,b) => a >= b));
This solution tries to get all valid sequences and returns the longes sequences for filtering the parts out.
It works by iterating the given array and checks if the values could build a sequence. If a value is given, which part result has a valid predecessor, the array is appended with this value. If not a backtracking is made and a sequence is searched with a valid predecessor.
act. array
value 7 3 4 4 5 1 23 7 comment
----- ------------------------ ---------------------------
7 7 add array with single value
3 7 keep
3 add array with single value
4 7 keep
3 4 add value to array
4 7 keep
3 4 4 add value to array
5 7 keep
3 4 4 5 add value to array
1 7 keep
3 4 4 5 keep
1 add array with single value
23 7 23 add value to array
3 4 4 5 23 add value to array
1 23 add value to array
7 7 23 keep
7 7 fork above, filter for smaller or equal and add value
3 4 4 5 23 keep
3 4 4 5 7 fork above, filter for smaller or equal and add value
1 23 keep
1 7 fork above, filter for smaller or equal and add value
function longestSequences(array, getValue = v => v) {
return array
.reduce(function (sub, value) {
var single = true;
sub.forEach(function (s) {
var temp;
if (getValue(s[s.length - 1]) <= getValue(value)) {
s.push(value);
single = false;
return;
}
// backtracking
temp = s.reduceRight(function (r, v) {
if (getValue(v) <= getValue(r[0])) {
r.unshift(v);
single = false;
}
return r;
}, [value]);
if (temp.length !== 1 && !sub.some(s => s.length === temp.length && s.every((v, i) => getValue(v) === getValue(temp[i])))) {
sub.push(temp);
}
});
if (single) {
sub.push([value]);
}
return sub;
}, [])
.reduce(function (r, a) {
if (!r || r[0].length < a.length) {
return [a];
}
if (r[0].length === a.length) {
r.push(a);
}
return r;
}, undefined);
}
function notInSequence(array, getValue = v => v) {
var longest = longestSequences(array, getValue);
return array.filter((i => a => a !== longest[0][i] || !++i)(0));
}
var array = [7, 3, 4, 4, 5, 1, 23, 7, 8, 15, 9, 2, 12, 13],
fDates = [['2015-02-03', 'name1'], ['2015-02-04', 'nameg'], ['2015-02-04', 'name5'], ['2015-02-05', 'nameh'], ['1929-03-12', 'name4'], ['2023-07-01', 'name7'], ['2015-02-07', 'name0'], ['2015-02-08', 'nameh'], ['2015-02-15', 'namex'], ['2015-02-09', 'namew'], ['1980-12-23', 'name2'], ['2015-02-12', 'namen'], ['2015-02-13', 'named']],
usuallyFailingButNotHere = [['2015-01-01'], ['2014-01-01'], ['2015-01-02'], ['2014-01-02'], ['2015-01-03'], ['2014-01-03'], ['2014-01-04'], ['2015-01-04'], ['2014-01-05'], ['2014-01-06'], ['2014-01-07'], ['2014-01-08'], ['2014-01-09'], ['2014-01-10'], ['2014-01-11']],
test2 = [['1975-01-01'], ['2015-02-03'], ['2015-02-04'], ['2015-02-04'], ['2015-02-05'], ['1929-03-12'], ['2023-07-01'], ['2015-02-07'], ['2015-02-08']];
console.log(longestSequences(array));
console.log(notInSequence(array));
console.log(notInSequence(fDates, a => a[0]));
console.log(longestSequences(usuallyFailingButNotHere, a => a[0]));
console.log(notInSequence(usuallyFailingButNotHere, a => a[0]));
console.log(longestSequences(test2, a => a[0]));
console.log(notInSequence(test2, a => a[0]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
This solution uses the function reduce and keeps the previously accepted date to make the necessary comparisons.
var fDates = [['2015-02-03', 'name1'], ['2015-02-04', 'nameg'], ['2015-02-04', 'name5'], ['2015-02-05', 'nameh'], ['1929-03-12', 'name4'], ['2023-07-01', 'name7'], ['2015-02-07', 'name0'], ['2015-02-08', 'nameh'], ['2015-02-15', 'namex'], ['2015-02-09', 'namew'], ['1980-12-23', 'name2'], ['2015-02-12', 'namen'], ['2015-02-13', 'named']],
results = fDates.reduce((acc, c, i, arr) => {
/*
* This function finds a potential valid sequence.
* Basically, will check if any next valid sequence is
* ahead from the passed controlDate.
*/
function sequenceAhead(controlDate) {
for (var j = i + 1; j < arr.length; j++) {
let [dt] = arr[j];
//The controlDate is invalid because at least a forward date is in conflict with its sequence.
if (dt > acc.previous && dt < controlDate) return true;
}
//The controlDate is valid because forward dates don't conflict with its sequence.
return false;
}
let [date] = c; //Current date in this iteration.
if (i > 0) { // If this is not the first iteration
if (date === acc.previous) return acc; // Same as previous date are skipped.
// If the current date is lesser than previous then is out of sequence.
// Or if there is at least valid sequence ahead.
if (date < acc.previous || sequenceAhead(date)) acc.results.push(c);
else acc.previous = date; // Else, this current date is in sequence.
}
else acc.previous = date; // Else, set the first date.
return acc;
}, { 'results': [] }).results;
console.log(results);
.as-console-wrapper { max-height: 100% !important; top: 0; }
All of previous answers focus on JavaScript and maybe they won't work
correctly. So I decided to add new answer that focused on
Algorithm.
As #Trees4theForest mentioned in his question and comments, he is looking for a solution for Longest Increase Subsequence and out of order dates are dates that aren't in Longest Increase Subsequence (LIS) set.
I used this method like below. In algorithm's point of view, it's true.
function longestIncreasingSequence(arr, strict) {
var index = 0,
indexWalker,
longestIncreasingSequence,
i,
il,
j;
// start by putting a reference to the first entry of the array in the sequence
indexWalker = [index];
// Then walk through the array using the following methodolgy to find the index of the final term in the longestIncreasing and
// a sequence (which may need altering later) which probably, roughly increases towards it - http://en.wikipedia.org/wiki/Longest_increasing_subsequence#Efficient_algorithms
for (i = 1, il = arr.length; i < il; i++) {
if (arr[i] < arr[indexWalker[index]]) {
// if the value is smaller than the last value referenced in the walker put it in place of the first item larger than it in the walker
for (j = 0; j <= index; j++) {
// As well as being smaller than the stored value we must either
// - be checking against the first entry
// - not be in strict mode, so equality is ok
// - be larger than the previous entry
if (arr[i] < arr[indexWalker[j]] && (!strict || !j || arr[i] > arr[indexWalker[j - 1]])) {
indexWalker[j] = i;
break;
}
}
// If the value is greater than [or equal when not in strict mode) as the last in the walker append to the walker
} else if (arr[i] > arr[indexWalker[index]] || (arr[i] === arr[indexWalker[index]] && !strict)) {
indexWalker[++index] = i;
}
}
// Create an empty array to store the sequence and write the final term in the sequence to it
longestIncreasingSequence = new Array(index + 1);
longestIncreasingSequence[index] = arr[indexWalker[index]];
// Work backwards through the provisional indexes stored in indexWalker checking for consistency
for (i = index - 1; i >= 0; i--) {
// If the index stored is smaller than the last one it's valid to use its corresponding value in the sequence... so we do
if (indexWalker[i] < indexWalker[i + 1]) {
longestIncreasingSequence[i] = arr[indexWalker[i]];
// Otherwise we need to work backwards from the last entry in the sequence and find a value smaller than the last entry
// but bigger than the value at i (this must be possible because of the way we constructed the indexWalker array)
} else {
for (j = indexWalker[i + 1] - 1; j >= 0; j--) {
if ((strict && arr[j] > arr[indexWalker[i]] && arr[j] < arr[indexWalker[i + 1]]) ||
(!strict && arr[j] >= arr[indexWalker[i]] && arr[j] <= arr[indexWalker[i + 1]])) {
longestIncreasingSequence[i] = arr[j];
indexWalker[i] = j;
break;
}
}
}
}
return longestIncreasingSequence;
}
With method above, we can find dates that is out of order like below:
// Finding Longest Increase Subsequence (LIS) set
var _longestIncreasingSequence = longestIncreasingSequence(fDates.map(([date]) => date));
// Out of order dates
var result = fDates.filter(([date]) => !_longestIncreasingSequence.includes(date));
Online demo(jsFiddle)
here is a simple self- explanatory solution. hope it will help you.
const findOutOfSequenceDates = items => {
items = items.map(d => d);
const sequence = [], outOfsequence = [];
sequence.push(items.shift());
const last = ind => sequence[sequence.length - ind][0];
items.forEach(item => {
const current = new Date(item[0]);
if (current >= new Date(last(1))) {
sequence.push(item);
} else if (current >= new Date(last(2))) {
outOfsequence.push(sequence.pop());
sequence.push(item);
} else {
outOfsequence.push(item);
}
});
return outOfsequence;
};
var fDates = [
['2015-02-03', 'name1'],
['2015-02-04', 'nameg'],
['2015-02-04', 'name5'],
['2015-02-05', 'nameh'],
['1929-03-12', 'name4'],
['2023-07-01', 'name7'],
['2015-02-07', 'name0'],
['2015-02-08', 'nameh'],
['2015-02-15', 'namex'],
['2015-02-09', 'namew'],
['1980-12-23', 'name2'],
['2015-02-12', 'namen'],
['2015-02-13', 'named'],
];
console.log(findOutOfSequenceDates(fDates));
Use the Javascript Date type. Compare with those objects. Very simplistically,
date1 = new Date(fDates[i, 0])
date2 = new Date(fDates[i+1, 0])
if (date2 < date1) { // or whatever comparison you want ...
// flag / print / alert the date
}
To clarify, This merely finds items out of sequence. You can do that with strings, as Jaromanda X pointed out. However, you use the phrase "way out of line"; whatever this means for you, Date should give you the ability to determine and test for it. For instance, is '2023-07-01' unacceptable because it's 8 years away, or simply because it's out of order with the 2015 dates? You might want some comparison to a simpler time span, such as one month, where your comparison will looks something like
if (date2-date1 > one_month)
Summary of your question
If I have understood your question correctly, you are trying to identify array entries that do not follow a chronological order based on the time/date property value.
Solution
Convert the date string / time into a UNIX time stamp (number of seconds lapsed since 01/jan/1970 at 00:00:00)
Using a loop, we can store the value against a previous reading per itenary, if the value is negative, this would indicate an error in the date lapse, if the value is positive, it would indicate the order is valid
When negative, we can create an array to denote the position of the reference array and its values allowing you to go back to the original array and review the data.
Example Code
var arrData = [
{date: '2015-02-03', value:'name1'},
{date: '2015-02-04', value:'nameg'},
{date: '2015-02-04', value:'name5'},
{date: '2015-02-05', value:'nameh'},
{date: '1929-03-12', value:'name4'},
{date: '2023-07-01', value:'name7'},
{date: '2015-02-07', value:'name0'},
{date: '2015-02-08', value:'nameh'},
{date: '2015-02-15', value:'namex'},
{date: '2015-02-09', value:'namew'},
{date: '1980-12-23', value:'name2'},
{date: '2015-02-12', value:'namen'},
{date: '2015-02-13', value:'named'}
];
var arrSeqErrors = [];
function funTestDates(){
var intLastValue = 0, intUnixDate =0;
for (x = 0; x <= arrData.length-1; x++){
intUnixDate = Date.parse(arrData[x].date)/1000;
var intResult = intUnixDate - intLastValue;
if (intResult < 0){
console.log("initeneration: " + x + " is out of sequence");
arrSeqErrors.push (arrData[x]);
}
intLastValue = intResult;
}
console.log("Items out of sequence are:");
console.log(arrSeqErrors);
}
funTestDates();

sorting of array manually in javascript

I have an array of strings like below.
ABC
QRS
DEF
HIJ
TUV
KLM
NOP
I need to sort this array in javascript in alphabetical order, except for few values which is already known. ie I need DEF and NOP comes in the first 2 positions and sort rest of the array alphabetically in ascending order. Here is what I've written to sort the entire array in alphabetical order, now I need the 2 values in the first 2 positions.
array.sort(function(a,b){return ((a < b) ? -1 : (a > b) ? 1 : 0)});
Expected result.
DEF
NOP
ABC
HIJ
KLM
QRS
TUV
The contents of the array is dynamic, so if the array has DEF or NOP, then those should be on top, if else, it should be sorted alphabetically. Whats the best way to approach this?
I think the most straightforward way would be to remove the known elements separately instead of trying to incorporate them into the sort. That way, you can also just sort without a comparison function.
function sortWithKnownPrefix(prefix, arr) {
// Get the non-prefix elements
var rest = arr.filter(function (item) {
return prefix.indexOf(item) === -1;
});
// Concatenate the prefix and the sorted non-prefix elements
return prefix.concat(rest.sort());
}
sortWithKnownPrefix(
["DEF", "NOP"],
["ABC", "QRS", "DEF", "HIJ", "TUV", "KLM", "NOP"]
)
// ["DEF", "NOP", "ABC", "HIJ", "KLM", "QRS", "TUV"]
If you want to allow for, count and hoist multiple instances of those strings: http://jsfiddle.net/4hgnjqas/1/
The following will count all known instances of the strings you want to hoist to the front, remove them from the existing array, sort it, then add the same number of "DEF"s and "NOP"s to the array.
var hoist = {"NOP":0, "DEF":0}
for(var p in hoist)
while(array.indexOf(p)>-1){
array.splice(array.indexOf(p),1);
hoist[p]++;
}
arr.sort();
for(var p in hoist){
for(var i=0;i<hoist[p];i++)
array.unshift(p);
}
console.log(array);
This will reposition 'DEF' and 'NOP' after sorting the rest of the items:
function customSort(array) {
array = array.sort(function(a,b){
return (a < b) ? -1 : (a > b) ? 1 : 0;
});
var NOPIndex = array.indexOf('NOP');
if (NOPIndex > -1)
array.unshift(array.splice(NOPIndex, 1)[0]);
var DEFIndex = array.indexOf('DEF');
if (DEFIndex > -1)
array.unshift(array.splice(DEFIndex, 1)[0]);
return array;
}
this could be the simpler one
var arr = ['ABC','QRS','DEF','HIJ','TUV','KLM','NOP']
var exclude = ['DEF', 'NOP'];
arr.sort(function(a,b) {
if(exclude.indexOf(a) > -1 && exclude.indexOf(b) > -1)
return ((a < b) ? -1 : (a > b) ? 1 : 0);
if(exclude.indexOf(b) > -1)
return 1;
return ((a < b) ? -1 : (a > b) ? 1 : 0)
});
alert(JSON.stringify(arr)) //result
JS Fiddle *UPDATED

JavaScript .sort override

I have an array of strings, which are all similar except for parts of them, eg:
["1234 - Active - Workroom",
"1224 - Active - Breakroom",
"2365 - Active - Shop"]
I have figured out that to sort by the ID number I just use the JavaScript function .sort(), but I cannot figure out how to sort the strings by the area (eg: "Workroom etc..").
What I am trying to get is:
["1224 - Active - Breakroom",
"2365 - Active - Shop",
"1234 - Active - Workroom"]
The "Active" part will always be the same.
From what I have found online, I have to make a .sort() override method to sort it, but I cannot figure out what I need to change inside the override method.
Example for you
var items = [
{ name: "Edward", value: 21 },
{ name: "Sharpe", value: 37 },
{ name: "And", value: 45 },
{ name: "The", value: -12 },
{ name: "Magnetic" },
{ name: "Zeros", value: 37 }
];
items.sort(function (a, b) {
if (a.name > b.name)
return 1;
if (a.name < b.name)
return -1;
// a must be equal to b
return 0;
});
You can make 1 object to describe your data .
Example
data1 = { id : 12123, status:"Active", name:"Shop"}
You can implement your logic in sort().
Return 1 if a > b ;
Return -1 if a < b
Return 0 a == b.
Array will automatically order follow the return
Hope it'll help.
You can give the sort method a function that compares two items and returns the order:
yourArray.sort(function(item1, item2){
// compares item1 & item2 and returns:
// -1 if item1 is less than item2
// 0 if equal
// +1 if item1 is greater than item2
});
Example in your case :
yourArray.sort(function(item1, item2){
// don't forget to check for null/undefined values
var split1 = item1.split(' - ');
var split2 = item2.split(' - ');
return split1[2] < split2[2] ? -1 : (split1[2] > split2[2] ? 1 : 0);
});
see Array.prototype.sort()
You don't have to override anything, just pass .sort custom function that will do the sorting:
var rsortby = {
id : /^(\d+)/,
name : /(\w+)$/,
status : /-\s*(.+?)\s*-/,
};
var r = rsortby['name'];
[
'1234 - Active - Workroom',
'1224 - Active - Breakroom',
'2365 - Active - Shop',
].
sort(function(a, b) {
var ma = a.match(r)[1];
var mb = b.match(r)[1];
return (ma != mb) ? (ma < mb ? -1 : 1) : 0;
});
// ["1224 - Active - Breakroom", "2365 - Active - Shop", "1234 - Active - Workroom"]
//

Javascript sort on on part of string

I have an array of strings that consist of an optional two-letter string signifying spring or fall, followed by a four-digit year, i.e. as one of the following examples:
var example_data = ["HT2014", "VT2013", "2017"];
I'd like to sort this array so that it is primarily sorted on the year (i.e. the four digits, as numbers) and then (if the years are equal) it is sorted so that VT is first, HT is in the middle and entries that do not specify spring or fall are last.
If I've understood the JavaScript sort() function correctly, I should be able to implement a sortFunction that tells me which of two objects should be first, and then just make a call to data.sort(sortFunction).
I've also started working on such a sortFunction, and come up with the following:
function specialSort(a,b) {
var as = a.split("T");
var bs = b.split("T");
if (as[1] != bs[1]) {
return as[1] - bs[1];
} else {
// The year is equal.
// How do I sort on term?
}
}
As the comments signify, I have no clue on what to do to get the sorting on "HT", "VT" and "" correct (except maybe a ridiculous series of nested ifs...). (Also, I know the above code will fail for the third item in the example data, since "2017.split("T") will only have 1 element. I'll deal with that...)
Is this a good approach? If yes - how do I complete the function to do what I want? If no - what should I do instead?
It could be shorter, but this approach calculates a sorting key first, which is then used to sort the array.
Generating the sorting key is very explicit and easy to understand, which always helps me when creating a sort algorithm.
// sorting key = <year> + ('A' | 'B' | 'C')
function getitemkey(item)
{
var parts = item.match(/^(HT|VT)?(\d{4})$/);
switch (parts[1]) {
case 'VT': return parts[2] + 'A'; // VT goes first
case 'HT': return parts[2] + 'B'; // HT is second
}
return parts[2] + 'C'; // no prefix goes last
}
function cmp(a, b)
{
var ka = getitemkey(a),
kb = getitemkey(b);
// simple key comparison
if (ka > kb) {
return 1;
} else if (ka < kb) {
return -1;
}
return 0;
}
["HT2014", "VT2013", "2017", 'HT2013', '2013'].sort(cmp);
I'd use a regular expression with captures and compare on the parts
function compare(a, b) {
var re = /([HV]T)?(\d\d\d\d)/;
var ma = re.exec(a);
var mb = re.exec(b);
// compare the years
if (ma[2] < mb[2])
return -1;
if (ma[2] > mb[2])
return 1;
// years are equal, now compare the prefixes
if (ma[1] == mb[1])
return 0;
if (ma[1] == 'VT')
return -1;
if (mb[1] == 'VT')
return 1;
if (ma[1] == 'HT')
return -1;
return 1;
}
I'll deal with that...
You can do that by getting the last item from the array, instead of the second:
var lastCmp = as.pop() - bs.pop();
if (lastCmp) // != 0
return lastCmp;
else
// compare on as[0] / bs[0], though they might be undefined now
how do I complete the function to do what I want?
You will need a comparison index table. Similiar to #Jack's switch statement, it allows you to declare custom orderings:
var orderingTable = {
"V": 1,
"H": 2
// …
},
def = 3;
var aindex = orderingTable[ as[0] ] || def, // by as[0]
bindex = orderingTable[ bs[0] ] || def; // by bs[0]
return aindex - bindex;
If you don't want a table like this, you can use an array as well:
var ordering = ["V", "H" /*…*/];
var *index = ordering.indexOf(*key)+1 || ordering.length+1;
I took the liberty of using underscore:
var example_data = ["2002","HT2014", "VT2013", "2017", "VT2002", "HT2013"];
var split = _.groupBy(example_data, function(val){ return val.indexOf('T') === -1});
var justYears = split[true].sort();
var yearAndTerm = split[false].sort(function(a,b){
var regex = /([HV])T(\d\d\d\d)/;
var left = regex.exec(a);
var right = regex.exec(b);
return left[2].localeCompare(right[2]) || right[1].localeCompare(left[1]);
});
var sorted = yearAndTerm.concat(justYears);
console.log(sorted);
Here is the fiddle: http://jsfiddle.net/8KHGu/ :)

Categories

Resources