In Javascript, how to apply a dynamically created function name - javascript

My goal is to efficiently apply a dynamically chosen set of transforms to each element of a matrix. I store the selected functions in an array, then apply each of them in a single pass thru the matrix.
My question is, how can I dynamically create the name of a function that I add to the array of functions?
This fiddle contains my attempt. My question is included in the comment block.
function dynam () {
var prepend = 'before - ';
var append = ' - after';
var whichCase = 'Upper';
var functionsToApply = [];
var matrix = [
['aBc', 'DeF'],
['ghi', 'JKL'],
];
var out = 'Initial: ' + matrix.join(' | ');
document.getElementById('output').innerHTML = out + '\n';
console.log(out);
// Set up transforms
if (whichCase == 'Lower') {
functionsToApply.push(function(v) {return v.toLowerCase();});
} else if (whichCase == 'Upper'){
functionsToApply.push(function(v) {return v.toUpperCase();});
}
// How can the function be defined dynamically?
// Perhaps something like:
// if(['Lower','Upper'].indexOf(whichCase) != -1) {
// functionsToApply.push(function(v) {'return v.to' + which + 'Case();'});
// }
if (prepend && prepend.length > 0 && prepend != 'none') {
functionsToApply.push(function(v) {return prepend + v;});
}
if (append && append.length > 0 && append != 'none') {
functionsToApply.push(function(v) {return v + append;});
}
// Apply all of the transforms to each of the elements of the matrix
matrix = matrix.map(function(row){
return row.map(function(val) {
for (var fn = 0; fn < functionsToApply.length; fn++) {
val = functionsToApply[fn](val);
}
return val;
})
});
out = 'Final: ' + matrix.join(' | ');
document.getElementById('output').innerHTML += out + '\n';
console.log(out);
}

I like to declare my functions in a hash in this case, then you can call them based on the value passed in, which is the key to the hash.
Updated: I've added a way to get the lower/upper function dynamically, and call it.
function dynam(whichCase, prepend, append, matrix) {
var functionHash = {
"Lower" : function(v) {return v.toLowerCase();},
"Upper" : function(v) {return v.toUpperCase();},
"Prepend" : function(v) {return prepend + v;},
"Append": function(v) {return v + append;}
}
// to actually get the case function based on the word passed in,
// you can do it this way.
var lowerUpperFunction = String.prototype['to' + whichCase + 'Case'];
var str = lowerUpperFunction.call("xyz");
console.log(str);
var functionsToApply = [];
var out = 'Initial: ' + matrix.join(' | ');
console.log(out);
// see how we just take the whichCase and make that a call to the hash?
functionsToApply.push(functionHash[whichCase]);
if (prepend && prepend.length > 0 && prepend != 'none') {
functionsToApply.push(functionHash["Prepend"]);
}
if (append && append.length > 0 && append != 'none') {
functionsToApply.push(functionHash["Append"]);
}
// Apply all of the transforms to each of the elements of the matrix
matrix = matrix.map(function(row){
return row.map(function(val) {
for (var fn = 0; fn < functionsToApply.length; fn++) {
console.log("applying function to val" + val );
val = functionsToApply[fn](val);
}
return val;
})
});
out = 'Final: ' + matrix.join(' | ');
return out;
}
var p = 'before - ';
var a = ' - after';
var w = 'Upper';
var m = [
['aBc', 'DeF'],
['ghi', 'JKL'],
];
console.log( dynam(w, p, a, m) );

Related

Javascript issue with precedence

I have built this function to replace a group of characters in a string by a random value from another list within a function:
function replaceExpr(a) {
var expToReplace = 0
var newSent = a
while (expToReplace == 0) {
if (a.search("zx") == -1) {
expToReplace = 1
} else {
var startPos = a.search("zx");
startPos += 2;
var endPos = a.search("xz");
var b = a.substring(startPos, endPos);
var fn = window[b];
if (typeof fn === "function") var newWord = fn();
final = newSent.replace("zx" + b + "xz", newWord);
newSent = final
a = a.replace("zx" + b + "xz", "")
}
}
return final
}
function appearance() {
var list = [
"attractive",
"fit",
"handsome",
"plain",
"short",
"tall",
"skinny",
"well-built",
"unkempt",
"unattractive"
]
return list[Math.floor(Math.random() * list.length)];
}
function personality() {
var list = [
"aggresive",
"absent-minded",
"cautious",
"detached from the real world",
"easygoing",
"focused",
"honest",
"dishonest",
"polite",
"uncivilized"
]
return list[Math.floor(Math.random() * list.length)];
}
An example :
var a = replaceExpr("Theodor is a zxappearancexz man. He seems rather zxpersonalityxz.")
alert(a)
// Theodor is a unattractive man. He seems rather cautious.
Everything works perfectly with the function but I have an issue related to it. As you can see, there's one grammar mistake : it's written "a unattractive" where it should be "an unattractive".
There's a function I usually use to to fix the a\an issue which is :
var AvsAnSimple = (function (root) {
//by Eamon Nerbonne (from http://home.nerbonne.org/A-vs-An), Apache 2.0 license
// finds if a word needs a "a" or "an" before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;–;r1;i1;g1;e.t1;r1.s;u1;i.r3. ;&;f;s9.,;?;R;f2.e.o.i1.c1.h;l1. ;p2.3;i1. ;r1.g;v3.a.e.i.t2.A;S;uc; ...b2.e;l;f.k2.a;i;m1;a1. .n3;a3; .n5.a;c;n;s;t;r1;y.e2; .i.i8.c2.o1.r1.p;u1.m;d1;i1.o;g1.n;l1.l;m1;o.n;s1.s;v1.o1;c.r5;a.e.i.l.o.s3. ;h;u1.r2;e.p3;a.e.i.t2.m;t;v.w1.a;xb. ;';,;.;8;b;k;l;m1;a.t;y1. ;y1.l;{1.a;|1.a;£1.8;À;Á;Ä;Å;Æ;É;Ò;Ó;Ö;Ü;à;á;æ;è;é1;t3.a;o;u;í;ö;ü1; .Ā;ā;ī;İ;Ō;ō;œ;Ω;α;ε;ω;ϵ;е;–2.e;i;ℓ;";
function fill(node) {
var kidCount = parseInt(dict, 36) || 0,
offset = kidCount && kidCount.toString(36).length;
node.article = dict[offset] == "." ? "a" : "an";
dict = dict.substr(1 + offset);
for (var i = 0; i < kidCount; i++) {
var kid = node[dict[0]] = {}
dict = dict.substr(1);
fill(kid);
}
}
fill(root);
return {
raw: root,
//Usage example: AvsAnSimple.query("example")
//example returns: "an"
query: function (word) {
var node = root, sI = 0, result, c;
do {
c = word[sI++];
} while ('"‘’“”$\''.indexOf(c) >= 0);//also terminates on end-of-string "undefined".
while (1) {
result = node.article || result;
node = node[c];
if (!node) return result;
c = word[sI++] || " ";
}
}
};
})({})
Now, the problem is that I can't find a way to use this function in conjunction with the replaceExpr. The following obviously wouldn't work because of order precedence :
var a = replaceExpr("Theodor is " + AvsAnSimple(zxappearancexz) + "man. He seems rather " + AvsAnSimple(zxpersonalityxz).")
I just recently started learning javascript so my knowledge is rather limited. Any ideas how I could overcome this?
Thank you!
You could use a regular expression to optionally match the " a " or "an" before your word in the input string and store that matched portion in a variable using the String.match() function, then check if that " a " or " an " exists in your matched string, do the manipulations you need to do and store that manipulated string in a separate variable, then use String.replace() to find that previously matched string again, and replace it wit
your manipulated string. The regular expression you could use for this is /(\san?\s)?(zx\w*zx)/gm
See the regular expression here for more context.
Thank you Joseph! With your help I managed to find something that works by using your regular expression. Here's my function :
function replaceExpr(a) {
var nbExprToReplace = 1;
while (nbExprToReplace == 1) {
if (a.search("zx") == -1) {
nbExprToReplace = 0;
} else {
var currentGroup = a.match(/(\san?\s)?(zx\w*xz)/);
var exprToChange = currentGroup[2];
exprToChange = exprToChange.slice(2,-2);
var exprToChange = window[exprToChange];
if (typeof exprToChange !== "function") {
alert("the keyword is not a recognized function!");
break;
} else {
exprToChange = exprToChange();
var final = exprToChange
};
if (currentGroup[1] === undefined) {
} else {
var newArticle = AvsAnSimple.query(exprToChange);
final = newArticle.concat(" " + final)
};
a = a.replace(currentGroup[0], " " + final);
};
};
return a;
};

Accessing js object issue

I have created an object of available_categories({category: coats-and-jackets}) and another object category_names_for_display({coats-and-jackets:Coats and Jackets}).
The intention is to use the 'key' (coats-and-jackets) from the loop of available_categories, to get the category_name_for_display (Coats & Jackets) from the second object.
// build array of available categories
var obj = available_categories.find(o=>o.category === cat);
if (!(obj) && cat && cat.length > 0) {
available_categories.push({
category: cat
});
}
//console.log('ac=' + available_categories);
// build array of category_names_for_display
var obj = category_names_for_display.find(o=>o.cat === category_name_for_display);
if (!obj && cat && cat.length > 0 && category_name_for_display) {
console.log('cat = ' + cat + 'cnfd= ' + category_name_for_display);
var arr = {};
arr[cat] = category_name_for_display;
category_names_for_display.push(arr);
new_var = category_names_for_display['cat'];
console.log('this ' + new_var);
}
if (available_categories.length > 0) {
//loop through the array to output more data
$.each(available_categories, function(k , v)
{
$.each(this, function(k , v)
{
var checked_status = '';
var selected_option_number = '';
var undo_label = '';
console.log('k= ' + k + 'V= ' + v);
// here is where I have something wrong :(
var catego = category_names_for_display['v'];
}
}
}
I am only getting the console to show the value is undefined. I need the category_name_for_display to be Coats & Jackets.
Just try to create a object and push.
if ( !obj && cat && cat.length > 0 && category_name_for_display )
{
var arr = {};
arr[cat] = category_name_for_display;
category_names_for_display.push(arr);
}
category_names_for_display is an array and the mistake is you are trying to access category_names_for_display as an object
You can modify you code as shown below to make your var catego store corect thing
$.each(this, function(k , v)
{
var checked_status = '';
var selected_option_number = '';
var undo_label = '';
console.log('k= ' + k + 'V= ' + v);
var catego = category_names_for_display.find(item => item === v);
}

How to convert from Path to XPath, given a browser event

On a MouseEvent instance, we have a property called path, it might look like this:
Does anybody know if there is a reliable way to translate this path array into an XPath? I assume that this path data is the best data to start from? Is there a library I can use to do the conversion?
This library looks promising, but it doesn't use the path property of an event: https://github.com/johannhof/xpath-dom
There's not a unique XPath to a node, so you'll have to decide what's the most appropriate way of constructing a path. Use IDs where available? Numeral position in the document? Position relative to other elements?
See getPathTo() in this answer for one possible approach.
PS: Taken from Javascript get XPath of a node
Another option is to use SelectorGadget from below link
https://dv0akt2986vzh.cloudfront.net/unstable/lib/selectorgadget.js
The actual code for the DOM path is at
https://dv0akt2986vzh.cloudfront.net/stable/lib/dom.js
Usage: on http://google.com
elem = document.getElementById("q")
predict = new DomPredictionHelper()
predict.pathOf(elem)
// gives "body.default-theme.des-mat:nth-child(2) div#_Alw:nth-child(4) form#f:nth-child(2) div#fkbx:nth-child(2) input#q:nth-child(2)"
predict.predictCss([elem],[])
// gives "#q"
CODE if link goes down
// Copyright (c) 2008, 2009 Andrew Cantino
// Copyright (c) 2008, 2009 Kyle Maxwell
function DomPredictionHelper() {};
DomPredictionHelper.prototype = new Object();
DomPredictionHelper.prototype.recursiveNodes = function(e){
var n;
if(e.nodeName && e.parentNode && e != document.body) {
n = this.recursiveNodes(e.parentNode);
} else {
n = new Array();
}
n.push(e);
return n;
};
DomPredictionHelper.prototype.escapeCssNames = function(name) {
if (name) {
try {
return name.replace(/\s*sg_\w+\s*/g, '').replace(/\\/g, '\\\\').
replace(/\./g, '\\.').replace(/#/g, '\\#').replace(/\>/g, '\\>').replace(/\,/g, '\\,').replace(/\:/g, '\\:');
} catch(e) {
console.log('---');
console.log("exception in escapeCssNames");
console.log(name);
console.log('---');
return '';
}
} else {
return '';
}
};
DomPredictionHelper.prototype.childElemNumber = function(elem) {
var count = 0;
while (elem.previousSibling && (elem = elem.previousSibling)) {
if (elem.nodeType == 1) count++;
}
return count;
};
DomPredictionHelper.prototype.pathOf = function(elem){
var nodes = this.recursiveNodes(elem);
var self = this;
var path = "";
for(var i = 0; i < nodes.length; i++) {
var e = nodes[i];
if (e) {
path += e.nodeName.toLowerCase();
var escaped = e.id && self.escapeCssNames(new String(e.id));
if(escaped && escaped.length > 0) path += '#' + escaped;
if(e.className) {
jQuery.each(e.className.split(/ /), function() {
var escaped = self.escapeCssNames(this);
if (this && escaped.length > 0) {
path += '.' + escaped;
}
});
}
path += ':nth-child(' + (self.childElemNumber(e) + 1) + ')';
path += ' '
}
}
if (path.charAt(path.length - 1) == ' ') path = path.substring(0, path.length - 1);
return path;
};
DomPredictionHelper.prototype.commonCss = function(array) {
try {
var dmp = new diff_match_patch();
} catch(e) {
throw "Please include the diff_match_patch library.";
}
if (typeof array == 'undefined' || array.length == 0) return '';
var existing_tokens = {};
var encoded_css_array = this.encodeCssForDiff(array, existing_tokens);
var collective_common = encoded_css_array.pop();
jQuery.each(encoded_css_array, function(e) {
var diff = dmp.diff_main(collective_common, this);
collective_common = '';
jQuery.each(diff, function() {
if (this[0] == 0) collective_common += this[1];
});
});
return this.decodeCss(collective_common, existing_tokens);
};
DomPredictionHelper.prototype.tokenizeCss = function(css_string) {
var skip = false;
var word = '';
var tokens = [];
var css_string = css_string.replace(/,/, ' , ').replace(/\s+/g, ' ');
var length = css_string.length;
var c = '';
for (var i = 0; i < length; i++){
c = css_string[i];
if (skip) {
skip = false;
} else if (c == '\\') {
skip = true;
} else if (c == '.' || c == ' ' || c == '#' || c == '>' || c == ':' || c == ',') {
if (word.length > 0) tokens.push(word);
word = '';
}
word += c;
if (c == ' ' || c == ',') {
tokens.push(word);
word = '';
}
}
if (word.length > 0) tokens.push(word);
return tokens;
};
DomPredictionHelper.prototype.decodeCss = function(string, existing_tokens) {
var inverted = this.invertObject(existing_tokens);
var out = '';
jQuery.each(string.split(''), function() {
out += inverted[this];
});
return this.cleanCss(out);
};
// Encode css paths for diff using unicode codepoints to allow for a large number of tokens.
DomPredictionHelper.prototype.encodeCssForDiff = function(strings, existing_tokens) {
var codepoint = 50;
var self = this;
var strings_out = [];
jQuery.each(strings, function() {
var out = new String();
jQuery.each(self.tokenizeCss(this), function() {
if (!existing_tokens[this]) {
existing_tokens[this] = String.fromCharCode(codepoint++);
}
out += existing_tokens[this];
});
strings_out.push(out);
});
return strings_out;
};
DomPredictionHelper.prototype.simplifyCss = function(css, selected_paths, rejected_paths) {
var self = this;
var parts = self.tokenizeCss(css);
var best_so_far = "";
if (self.selectorGets('all', selected_paths, css) && self.selectorGets('none', rejected_paths, css)) best_so_far = css;
for (var pass = 0; pass < 4; pass++) {
for (var part = 0; part < parts.length; part++) {
var first = parts[part].substring(0,1);
if (self.wouldLeaveFreeFloatingNthChild(parts, part)) continue;
if ((pass == 0 && first == ':') || // :nth-child
(pass == 1 && first != ':' && first != '.' && first != '#' && first != ' ') || // elem, etc.
(pass == 2 && first == '.') || // classes
(pass == 3 && first == '#')) // ids
{
var tmp = parts[part];
parts[part] = '';
var selector = self.cleanCss(parts.join(''));
if (selector == '') {
parts[part] = tmp;
continue;
}
if (self.selectorGets('all', selected_paths, selector) && self.selectorGets('none', rejected_paths, selector)) {
best_so_far = selector;
} else {
parts[part] = tmp;
}
}
}
}
return self.cleanCss(best_so_far);
};
DomPredictionHelper.prototype.wouldLeaveFreeFloatingNthChild = function(parts, part) {
return (((part - 1 >= 0 && parts[part - 1].substring(0, 1) == ':') &&
(part - 2 < 0 || parts[part - 2] == ' ') &&
(part + 1 >= parts.length || parts[part + 1] == ' ')) ||
((part + 1 < parts.length && parts[part + 1].substring(0, 1) == ':') &&
(part + 2 >= parts.length || parts[part + 2] == ' ') &&
(part - 1 < 0 || parts[part - 1] == ' ')));
};
DomPredictionHelper.prototype.cleanCss = function(css) {
return css.replace(/\>/, ' > ').replace(/,/, ' , ').replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '').replace(/,$/, '');
};
DomPredictionHelper.prototype.getPathsFor = function(arr) {
var self = this;
var out = [];
jQuery.each(arr, function() {
if (this && this.nodeName) {
out.push(self.pathOf(this));
}
})
return out;
};
DomPredictionHelper.prototype.predictCss = function(s, r) {
var self = this;
if (s.length == 0) return '';
var selected_paths = self.getPathsFor(s);
var rejected_paths = self.getPathsFor(r);
var css = self.commonCss(selected_paths);
var simplest = self.simplifyCss(css, selected_paths, rejected_paths);
// Do we get off easy?
if (simplest.length > 0) return simplest;
// Okay, then make a union and possibly try to reduce subsets.
var union = '';
jQuery.each(s, function() {
union = self.pathOf(this) + ", " + union;
});
union = self.cleanCss(union);
return self.simplifyCss(union, selected_paths, rejected_paths);
};
DomPredictionHelper.prototype.fragmentSelector = function(selector) {
var self = this;
var out = [];
jQuery.each(selector.split(/\,/), function() {
var out2 = [];
jQuery.each(self.cleanCss(this).split(/\s+/), function() {
out2.push(self.tokenizeCss(this));
});
out.push(out2);
});
return out;
};
// Everything in the first selector must be present in the second.
DomPredictionHelper.prototype.selectorBlockMatchesSelectorBlock = function(selector_block1, selector_block2) {
for (var j = 0; j < selector_block1.length; j++) {
if (jQuery.inArray(selector_block1[j], selector_block2) == -1) {
return false;
}
}
return true;
};
// Assumes list is an array of complete CSS selectors represented as strings.
DomPredictionHelper.prototype.selectorGets = function(type, list, the_selector) {
var self = this;
var result = true;
if (list.length == 0 && type == 'all') return false;
if (list.length == 0 && type == 'none') return true;
var selectors = self.fragmentSelector(the_selector);
var cleaned_list = [];
jQuery.each(list, function() {
cleaned_list.push(self.fragmentSelector(this)[0]);
});
jQuery.each(selectors, function() {
if (!result) return;
var selector = this;
jQuery.each(cleaned_list, function(pos) {
if (!result || this == '') return;
if (self._selectorGets(this, selector)) {
if (type == 'none') result = false;
cleaned_list[pos] = '';
}
});
});
if (type == 'all' && cleaned_list.join('').length > 0) { // Some candidates didn't get matched.
result = false;
}
return result;
};
DomPredictionHelper.prototype._selectorGets = function(candidate_as_blocks, selector_as_blocks) {
var cannot_match = false;
var position = candidate_as_blocks.length - 1;
for (var i = selector_as_blocks.length - 1; i > -1; i--) {
if (cannot_match) break;
if (i == selector_as_blocks.length - 1) { // First element on right.
// If we don't match the first element, we cannot match.
if (!this.selectorBlockMatchesSelectorBlock(selector_as_blocks[i], candidate_as_blocks[position])) cannot_match = true;
position--;
} else {
var found = false;
while (position > -1 && !found) {
found = this.selectorBlockMatchesSelectorBlock(selector_as_blocks[i], candidate_as_blocks[position]);
position--;
}
if (!found) cannot_match = true;
}
}
return !cannot_match;
};
DomPredictionHelper.prototype.invertObject = function(object) {
var new_object = {};
jQuery.each(object, function(key, value) {
new_object[value] = key;
});
return new_object;
};
DomPredictionHelper.prototype.cssToXPath = function(css_string) {
var tokens = this.tokenizeCss(css_string);
if (tokens[0] && tokens[0] == ' ') tokens.splice(0, 1);
if (tokens[tokens.length - 1] && tokens[tokens.length - 1] == ' ') tokens.splice(tokens.length - 1, 1);
var css_block = [];
var out = "";
for(var i = 0; i < tokens.length; i++) {
if (tokens[i] == ' ') {
out += this.cssToXPathBlockHelper(css_block);
css_block = [];
} else {
css_block.push(tokens[i]);
}
}
return out + this.cssToXPathBlockHelper(css_block);
};
// Process a block (html entity, class(es), id, :nth-child()) of css
DomPredictionHelper.prototype.cssToXPathBlockHelper = function(css_block) {
if (css_block.length == 0) return '//';
var out = '//';
var first = css_block[0].substring(0,1);
if (first == ',') return " | ";
if (jQuery.inArray(first, [':', '#', '.']) != -1) {
out += '*';
}
var expressions = [];
var re = null;
for(var i = 0; i < css_block.length; i++) {
var current = css_block[i];
first = current.substring(0,1);
var rest = current.substring(1);
if (first == ':') {
// We only support :nth-child(n) at the moment.
if (re = rest.match(/^nth-child\((\d+)\)$/))
expressions.push('(((count(preceding-sibling::*) + 1) = ' + re[1] + ') and parent::*)');
} else if (first == '.') {
expressions.push('contains(concat( " ", #class, " " ), concat( " ", "' + rest + '", " " ))');
} else if (first == '#') {
expressions.push('(#id = "' + rest + '")');
} else if (first == ',') {
} else {
out += current;
}
}
if (expressions.length > 0) out += '[';
for (var i = 0; i < expressions.length; i++) {
out += expressions[i];
if (i < expressions.length - 1) out += ' and ';
}
if (expressions.length > 0) out += ']';
return out;
};

Finding an undefined with first string in the array

I am doing the following:
<p>1983 (on television), 1984 (in theatres)</p>
The I run
var d;
var dateText = $("p").text().split(/\s+/g);
for(var i = 0; i < dateText.length; i++) {
d += dateText[i] + ' ';
}
var words = d.replace("–", " ").replace("-", " ").replace(",", " ").replace("/", " ").split(' ');
words = $.grep(words, function(n, i){
return (n !== "" && n != null);
});
var array = words;
var newArray = array.filter(function(v){return v!==''});
console.log(newArray);
["undefined1983", "(on", "television)", "1984", "(in", "theatres)"]
I shouldn't have undefined1983 but 1983
jsFiddle
Also if I do:
var d;
var spacetime = [];
spacetime.push({
Title : [],
Space : [],
Time : {
days : [],
months : [],
years : [],
suffixes : []
},
articleIdPush : [],
originalFullDate : [],
curArtLangPrefix : ["en"],
SingleTranslatedArticle : [],
});
var dateText = $("p").text().split(/\s+/g);
for(var i = 0; i < dateText.length; i++) {
d += dateText[i] + ' ';
}
var words = d.replace("–", " ").replace("-", " ").replace(",", " ").replace("/", " ").split(' ');
words = $.grep(words, function(n, i){
return (n !== "" && n != null);
});
var array = words;
var newArray = array.filter(function(v){return v!==''});
for (const word of newArray) {
if (months.has(word)) {
spacetime[counter].Time.months.push(word);
} else if (+word < 32) {
spacetime[counter].Time.days.push(+word);
} else if (+word < 2200) {
spacetime[counter].Time.years.push(+word);
} else if (/\w+/.test(word)) {
spacetime[counter].Time.suffixes.push(word);
}
}
console.log(spacetime);
I get
(index):90 Uncaught ReferenceError: months is not defined
I should have the defined array with the correct objects in it.
jsFiddle 2
The problem was with:
var d;
For the first iteration of your loop where you concatenate d onto itself with d +=, d is undefined. When I specified var d = ''; it works as expected.
Here's the working jsFiddle.

Sorting object in javascript (by number)

Ineed help with correct sorting in created object.
Object (in for loop):
var labelD = $("#crpc-page label[for='crpc-" + i + "-date']").text();
var valueD = $("#crpc-" + i + "-date").val();
var labelV = $("#crpc-page label[for='crpc-" + i + "-value']").text();
var valueV = $("#crpc-" + i + "-value").val();
console.log("i:" + labelD + " => " + valueD);
console.log("i:" + labelV + " => " + valueV);
dni = Date.parse(valueD);
var sortowanie = {};
var nr = "numer";
var dataD = "dataD";
var wartosc = "wartosc";
sortowanie[nr] = dni;
sortowanie[dataD] = valueD;
sortowanie[wartosc] = valueV;
all_dates.push(sortowanie);
Sorting function
function compare(a, b) {
if (a.numer < b.numer) return -1;
if (a.numer > b.numer) return 1;
return 0;
}
all_dates.sort(compare);
Second alternative sorting function:
function sortElement() {
all_dates.sort(function(a, b){
return a.numer-a.numer;
});
}
sortElement();
And now. My problem is that this function sorts only numer value not all objects inside { ... } .
Example
console returns:
[
{"numer":1428530400000,"dataD":"04/09/2015","wartosc":"3"},
{"numer":1441058400000,"dataD":"09/01/2015","wartosc":"1"},
{"numer":1441576800000,"dataD":"09/07/2015","wartosc":"2"}
]
I wish to recive:
[
{"numer":1441058400000,"dataD":"09/01/2015","wartosc":"1"},
{"numer":1441576800000,"dataD":"09/07/2015","wartosc":"2"},
{"numer":1428530400000,"dataD":"04/09/2015","wartosc":"3"}
]
My brain burns, and I dont know how to switch all elements inside {}
Thanks,
Fantazy
all_dates.sort(function(a,b){
return b.numer-a.numer;
});
It is working according to your need.
Your date parse does not work because it is not a US date.
Instead use
var parts = valueD.split("/");
dni = new Date(parts[2],parts[1]-1,parts[0]).getTime();
DEMO:
function compare(a, b) {
if (a.numer < b.numer) return -1;
if (a.numer > b.numer) return 1;
return 0;
}
function getEURTime(str) {
var parts = str.split("/");
return new Date(parts[2],parts[1]-1,parts[0]).getTime();
}
var EUR = [
{"dataD":"04/09/2015","wartosc":"3"},
{"dataD":"09/01/2015","wartosc":"1"},
{"dataD":"09/07/2015","wartosc":"2"}
]
for (var i=0;i<EUR.length;i++) {
EUR[i].numer=getEURTime(EUR[i].dataD);
}
console.log(EUR.sort(compare))

Categories