How to get the last element of a json file with jquery - javascript

$.getJSON('./file-read?filename='+filename+'&parameter='+parameter, function(data) {
var firstElement = data[0][0];
var lastElement = ?
});
I try to find out the last Element in my JSON file.
My JSON File looks like this:
[[1392418800000,6.9],[1392419400000,7],[1392420000000,7.1],[1392420600000,7.2],[1392421200000,7.2]]
can anybody help me to read extract the last date(1392421200000) ?

Just pick the (length - 1)th element with this:
var lastElement = data[data.length-1][0];
Another way is to use array methods, e.g. pop which will return the last element of the array:
var lastElement = data.pop()[0];
N.B.: The first approach is the fastest way of picking the last element, however the second approach will implicitly remove the last element from data array. So if you plan to use the initial array later in your code, be sure to use either the first method or alternative solution provided by #matewka.

VisioN's answer is nice and easy. Here's another approach:
var lastElement = data.slice(-1)[0];
// output: [1392421200000,7.2]
Negative number in the slice method makes the slice count from the end of the array. I find this method more compact and simpler but the disadvantage is that it returns a smaller, 1-element array instead of the element you wanted to fetch. If you want to fetch only the timestamp you'd have to add another [0] to the end of the expression, like this:
var lastElement = data.slice(-1)[0][0];
// output: 1392421200000

You can use :
var data = " any json data";
var lastelement = data[ Object.keys(obj).sort().pop() ];
Object.keys (ES5, shimmable) returns an array of the object's keys. We then sort them and grab the last one.

Related

insertBefore function for arrays and/or HTMLCollections?

Does there exist a function in vanilla JavaScript or jQuery that operates similarly to Node.insertBefore(), but for arrays and/or HTMLCollections?
An example could look something like:
var list = document.getElementsByClassName("stuff");
var nodeToMove = list[0];
var otherNode = list[4];
list.insertBefore(nodeToMove, otherNode);
Basically I'm trying to perform insertBefore() without manipulating the actual DOM, as I want the changes to only be applied to the DOM under certain conditions. If those conditions are met, then I would perform insertBefore() on the actual nodes.
To clarify, I'm looking for a function that would insert an element before a target element at a given index in an array, not necessarily at a given index. Examples I've seen using splice() usually insert an element at a given index, which sometimes puts the element before the target element, and sometimes after, depending on where the element to be moved originally was in the array. I'm looking for something that would reliably put the element to be moved before the target element.
HTMLCollection does not have an insertBefore method. jQuery can apply any jQuery methods both to a single element being selected, as well as many.
https://api.jquery.com/insertBefore/
There is no single method to do this in one step, but there doesn't need to be. If you convert the collection to an Array, you can call the Array.prototype.splice() method to achieve the same result.
Here's an example:
let ary = [1,2,3,4,5];
// Swap 2 and 3
// Start at the 3rd item and remove one item (3).
// Store the removed item
let removed = ary.splice(2,1);
// Start at the second item, don't remove anything, insert the removed
// item at that position
ary.splice(1,null,removed[0]);
// Log the result
console.log(ary);
And, with that knowledge, you can create your own more easily callable function:
let ary = [1,2,3,4,5];
function insertBefore(ary, newItem, target){
ary.splice(target,null,newItem);
}
// Insert 999 before the 3rd array item
insertBefore(ary,999,2)
console.log(ary);
You need to get the index you want, then use Array.splice.
Myself I would do something like this :
const myArr = ['Aurore', 'Dimitri', 'Alban', 'Frédéric'];
const insertBeforeThis = 'Alban';
const eltToInsert = 'Laura';
const index = myArr.findIndex(name => name === insertBeforeThis);
myArr.splice(index, 0, eltToInsert);
Please feel free to try it out in your browser's console. Note i used const for my array, as it fixes the type of the variable as an array but allow me to manipulate it.
MDN: Array.prototype.findIndex()
stackoverflow: How to insert an item into an array at a specific index (JavaScript)?
Have a happy coding time!

Select elements from a Javascript Array using one of the elements as a reference point

I'm wondering if it's possible to pull a certain number of elements out of a Javascript array and insert them into a new array, while using one of the elements as a reference point?
This is what I'm trying to do, imagine I have an array like this:
var firstarray = [
475387453,
286235425,
738264536,
196792345,
834532623,
253463455,
535273456];
And then I have a variable that equals the number 286235425:
var element = 286235425;
I have another variable that equals the number 3:
var thenumber = 3;
What I want to do is go through the array, select the 3 elements that come after the ''var element'' number, and store them in a new array named "second array".
So with the above example the result should be:
var secondarray = [
738264536,
196792345,
834532623];
I've seen some questions that talked about filtering array elements, but I haven't been able to find anything about selecting elements in the above way. Is such a thing even possible?
I know it's possible to trim elements from the beginning and end of the array, but as the array will always be a different length whenever the function runs, this method isn't suitable for this problem.
Any help with this would be really appreciated,
Thank you in advance!
You can do this with splice and indexOf
var firstarray = [
475387453,
286235425,
738264536,
196792345,
834532623,
253463455,
535273456
], element = 286235425, thenumber = 3;
var secondarray = firstarray.splice(firstarray.indexOf(element)+1, thenumber);
console.log(secondarray)
Grab the index where element is in the array using indexOf:
var index = firstarray.indexOf(element);
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
Use slice to grab the elements from the array from the next index to the next index + thenumber
var secondarray = firstarray.slice(index + 1, index + 1 + thenumber);
The slice() method returns a shallow copy of a portion of an array into a new array object.
DEMO

How to access element in JSON and Javascript

How do I access something like this with Javascript and Jquery?
"condition" : [{"conditionId":["3000"],"conditionDisplayName":["Used"]}]
(this is just an excerpt)
I tried using item.condition and I got:
[{"conditionId":["3000"],"conditionDisplayName":["Used"]}] as a result.
How do I get the conditionDisplayName?
I've also tried using : item.condition.conditionDisplayName but it doesn't work nor does item.condition[1]
You're almost there but your condition is an array with one object so you need to use the array notation to access it:
var displayName = item.condition[0].conditionDisplayName;
If there could be more than one object in the array, you can use a loop:
for(var i=0; i<item.condition.length; i++) {
console.log( item.condition[i].conditionDisplayName );
}
condition is an array, as is conditionDisplayName, so you will need to access their members using an index. For example, to get the first displayName of the first condition you would do:
var displayName = item.condition[0].conditionDisplayName[0]
You can use array index to get the object
var displayName = obj.condition[0].conditionDisplayName;
In your case you should try:
item.condition[0].conditionDisplayName
var array = [{"conditionId":["3000"],"conditionDisplayName":["Used"]}]
// Not right - show ["Used"]
console.log(array[0].conditionDisplayName);
// Right - show "Used"
console.log(array[0].conditionDisplayName[0]);
You can see this here: http://jsfiddle.net/bs9kx/

Using a variable as an array parameter in javascript?

I want to use a variable as the index parameter in an array but for some reason it's coming up as "undefined" when I do it this way. Any ideas?
var object_number = [];
var x = 1;
function create_new_object()
{
object_number[x] = new happy_object();
x++;
}
Array indices start at zero in JavaScript. When x starts at 1, there's an undefined element in the first position of the array. Start at x=0 instead.
There's a better way to do this, however. Instead of manually keeping track of the last element in the list, you can just use Array.push() to add a new element onto the end.
var object_number = [];
function create_new_object()
{
object_number.push(new happy_object());
}
When you want to find out how many elements are in the array, use Array.length (or the number returned by Array.push()).
Further reference: Array # MDC.
your object_number is an empty array with no elements. Hence you are getting this error.
To add elements to array, you need to use push method.
object_number.push(new happy_object() );
Also you need to start your array index from 0 instead of 1. i.e. your x should be 0.
In addition to the previous answers:
Unlike "normal" languages (which use block-scope), javascript uses function-scope.
So be shure x exists in side your function-scope when you use it like that.
you can't mess with array keys too too much in js - if you want a more solid, definable relationship, you'll need to mimic an associative array by doing:
var object_number = {};
var x = 1;
function create_new_object() {
object_number[x] = new happy_object();
}
Also, I'd combine your var statements. Makes variable/function hoisting a bit clearer.
var object_number = {}
, x = 1;

How to manipulate string in an array

I have an array that contain some fields
like this
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_18
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_19
I want to create a new array or manipulate this array to contain only
sid = {25,26,27}
from
_SID_25
_SID_26
_SID_27
where sid will be my array containing sid's extracted from above array
with pattern _SID_
I have to do this in jquery or javascript
use jquery map + regexp
var arr= ['tl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17',
'ctl00_ctl00_cphBody_bodycph_content_rdo_SID_26_SortOrder_18',
'ctl00_ctl00_cphBody_bodycph_content_rdo_SID_27_SortOrder_19']
var out = $(arr).map(function(){
return this.match(/SID_(.*?)_/)[1];
});
out should be an array of the values..
(assuming all the values in the array do match the pattern)
I would use regex here
var sid = []
var matches = "ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17".match(/_SID_(\d+)/);
if(matches) sid.push(parseInt(matches[1]));
This solution is totally reliant on the overall string form not changing too much, ie the number of "underscores" not changing which seems fragile, props given to commenter below but he had the index wrong. My original solution first split on "SID_" since that seemed more like a key that would always be present in the string going forward.
Given:
s = "ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25344_SortOrder_17"
old solution:
array.push(parseInt(s.split("SID_")[1].split("_")[0]))
new solution
array.push(parseInt(s.split("_")[7])

Categories

Resources