Finding an undefined with first string in the array - javascript

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.

Related

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);
}

Increment digit part of string in JavaScript

I have a string that contains digit at the end. I want to increase the digit part by 1 when some actions happened.
e.g.
var myString = 'AA11111'
increaseStringValue(myString)
# myString new value => 'AA11112'
also how can I increase chars when string value reached to 'AA99999' so new value of string will be 'AB11111'?
You can split char and digit parts so you can handle them separately.
like:
function increaseStringValue(str){
let charPart = str.substring(0,2);
let digitPart = str.substring(2);
digitPart = +digitPart+1
if(digitPart >= 99999){
digitPart = 11111;
if(charPart[1] == 'Z'){
if(charPart[0] == 'Z'){
throw 'Overflow happened'
}
charPart = String.fromCharCode(charPart.charCodeAt(0)+1) + 'A'
}else{
charPart = charPart[0] + String.fromCharCode(charPart.charCodeAt(1)+1)
}
}
return charPart + digitPart;
}
increaseStringValue('AA11111'); // 'AA11112'
increaseStringValue('AA99999'); // 'AB11111'
increaseStringValue('AZ99999'); // 'BA11111'
increaseStringValue('ZZ99999'); // Exception: Overflow happened
This links will be helpful for you:
ASCII CODES
what is a method that can be used to increment letters?
Edit:
Following function will be suite for unknown length string with dynamic position of char and digit.
function increaseStringValue(str) {
let charOverFlowed = true;
let result = ""
for (let i = str.length - 1; i >= 0; i--) {
let currentChar = str[i];
if ('123456789'.indexOf(currentChar) !== -1) {
if (charOverFlowed) {
currentChar = +currentChar + 1
charOverFlowed = false;
}
if (currentChar > 9) {
currentChar = 1;
charOverFlowed = true;
}
} else if (charOverFlowed) {
currentChar = String.fromCharCode(currentChar.charCodeAt(0) + 1)
charOverFlowed = false;
if (currentChar > 'Z') {
if(i == 0){
throw 'Overflow Happened'
}
currentChar = 'A'
charOverFlowed = true
}
}
result = currentChar + result;
}
return result;
}
increaseStringValue('AAAACA')
// "AAAACB"
increaseStringValue('AAAACA1111')
// "AAAACA1112"
increaseStringValue('A1')
// "A2"
increaseStringValue('Z')
// Uncaught Overflow Happened
increaseStringValue('A1999')
// "A2111"
function increaseStringValue(myString){
return myString.replace(/\d+/ig, function(a){ return a*1+1;});
}
console.log(increaseStringValue("asg61"));
And for next question:
function increaseStringValue(myString){
return myString.replace(/(A)(\d+)/ig, function(a, b, c){
var r = c*1+1; return r==99999+1?"B11111":"A"+r;
});
}
console.log(increaseStringValue("AA99999"));
And Whole way:
function increaseStringValue(myString){
return myString.replace(/([a-e])(\d+)/ig, function(a, b, c){
var r = c*1+1; return r==99999+1?String.fromCharCode(a.charCodeAt(0)+1)+"11111":b+r;
});
}
console.log(increaseStringValue("AB99999"));
Please find the snippet useful. If this is what you are expecting.
let stringNum = 'AA11111';//initialise string
let clickTriggered = ()=>{
let startString = "AA";
let newNum = ()=>{
let numberPart = stringNum.split("AA")[1];
let lastChar = stringNum[stringNum.length-1];
return Number(numberPart) != NaN || Number(numberPart) <= 99999 ? Number(numberPart)+1 : 11111;
};
stringNum = `${startString}${newNum()}`
console.log(stringNum)
}
<h1 onclick="clickTriggered()">click here</h1>
You can use String#replace and provide your increment logic in the function callback of the string#replace.
const increaseStringValue = (str) => str.replace(/\d+$/, n => n === '99999' ? 11111 : +n + 1);
console.log(increaseStringValue('AA99999'));
console.log(increaseStringValue('AA11315'));
console.log(increaseStringValue('AA11111'));
I solve this with this solution
let app = new Vue({
el: '#app',
data: {
text: "AA995"
},
methods: {
addOneString: function(str) {
var alphabet = 'abcdefghijklmnopqrstuvwxyz',
length = alphabet.length,
result = str,
i = str.length,
value = str;
while(i >= 0) {
var last = str.charAt(--i),
next = '',
carry = false;
if (isNaN(last)) {
index = alphabet.indexOf(last.toLowerCase());
if (index === -1) {
next = last;
carry = true;
}
else {
var isUpperCase = last === last.toUpperCase();
next = alphabet.charAt((index + 1) % length);
if (isUpperCase) {
next = next.toUpperCase();
}
carry = index + 1 >= length;
if (carry && i === 0) {
var added = isUpperCase ? 'A' : 'a';
result = added + next + result.slice(1);
break;
}
}
}
else {
next = +last + 1;
if(next > 9) {
next = 0;
carry = true;
}
if (carry && i === 0) {
result = '1' + next + result.slice(1);
break;
}
}
result = result.slice(0, i) + next + result.slice(i + 1);
if (!carry) {
break;
}
}
console.log("result",result);
if (value !== result ) this.text = result;
}
}
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div class="container" id="app">
<button #click="addOneString(text)">Add one</button>
</br>
<p> {{text}} </p>
</div>

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;
};

In Javascript, how to apply a dynamically created function name

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) );

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