How can I get the highest key in an array like that:
foo[0] == undefined
foo[1] == "bar"
foo[2] == undefined
foo[3] == undefined
foo[4] == "bar"
foo.length returns me 2, so if i iterate foo.length times, I'll never get the last value.
Or is there a way to count an array considering the undefined values as well?
I am unsure why your code is not working, .length on an array like that shows 5 correctly in my example here
However, if you do not set values at all on specific indexes, you can do this :
var foo = [];
foo[1] = "bar";
foo[4] = "bar";
//grab existing indexes that have values assigned
var indexes = foo.map(function(val, idx) { return idx; });
//get the last one, this + 1 is your real length
var realLength = indexes[indexes.length - 1] + 1;
console.log("Real length: ", realLength);
//iterate using for loop
for(var i=0; i<realLength; i++) {
var val = foo[i];
console.log(i, val);
}
Highest Key
var index = foo.lastIndexOf(foo.slice(-1)[0]);
Related
I had to remove same data in array.
I found this code and its work exactly the way i want but I can not understand part of this code.
please explain this code and WHAT IS THIS >>> a[this[i]] <<<
Array.prototype.unique = function() {
var a = {}; //new Object
for (var i = 0; i < this.length; i++) {
if (typeof a[this[i]] == 'undefined') {
a[this[i]] = 1;
}
}
this.length = 0; //clear the array
for (var i in a) {
this[this.length] = i;
}
return this;
};
Please see the comments before each line that explain that line of code
//added unique function to prototype of array so that all array can have unique //function access
Array.prototype.unique = function() {
//creating a temp object which will hold array values as keys and
//value as "1" to mark that key exists
var a = {}; //new Object
//this points to the array on which you have called unique function so
//if arr = [1,2,3,4] and you call arr.unique() "this" will point to
//arr in below code iterating over each item in array
for (var i = 0; i < this.length; i++) {
//idea is to take the value from array and add that as key in a so
//that next time it is defined. this[i] points to the array item at
//that index(value of i) //and a[this[i]] is adding a property on a
//with name "this[i]" which is the value //at that index so if value
//at that index is lets say 2 then a[this[i]] is //referring to
//a["2"].thus if 2 exists again at next index you do not add it to a
//again as it is defined
if (typeof a[this[i]] == 'undefined') {
a[this[i]] = 1;
}
}
this.length = 0; //clear the array
//now in a the properties are unique array items you are just looping
//over those props and adding it into current array(this) in which
//length will increase every //time you put a value
for (var i in a) {
this[this.length] = i;
}
//at the end returning this which is the modified array
return this;
};
//Edit
stored value of a[this[i]] is 1 for all the keys in a it will be one.
you start with
arr = [1,2,3,2,3,4];
when you call arr.unique
the code in the first loop creates a something like this
a = {
"1":1,
"2":1,
"3":1,
"4":1
}
so you can see that only unique values are as properties in a.
Now in the for-in loop you are just taking the keys of a(ie 1,2,3,4) and adding it to the array(this).
Hope this helps let me know if you need more details
a[this[i]] =>
this[i] -> get i element from current object, in this case it's Array.
a[] -> get element from var a at position specified in [], in this case what value is inside this[i]
I'm trying to access array which is property of an object, but I can only access letters from property name.
var obj = {};
obj.line0=[0,0];
obj.line1=[0,50];
var pointsLenght = 8;
//things above are just test case sandbox representing small amount of real data
var createPoints = function(obj){
var i;
for(var x in obj){
if (obj.hasOwnProperty(x)) {
for (i=0;i<pointsLenght;i++){
if (i%2==0){
x[i]=i*50;
}
else {
x[i]=x[1];
}
console.log(i+" element of array "+x+" is equal "+x[i]);
}
}
}
return obj;
}
And this is what I get in console (Firefox 47.0):
0 element of array line0 is equal l
1 element of array line0 is equal i
2 element of array line0 is equal n
3 element of array line0 is equal e
4 element of array line0 is equal 0
5 element of array line0 is equal undefined
6 element of array line0 is equal undefined
7 element of array line0 is equal undefined
How to access array?
You are accessing the property name, that is a string. ("line0" and "line1")
For accessing the array belongs to that property name, Just write your code like,
var createPoints = function(obj){
var i;
for(var x in obj){
if (obj.hasOwnProperty(x)) {
for (i=0;i<pointsLenght;i++){
if (i%2==0){
obj[x][i]=i*50;
//obj[x] will give you the array belongs to the property x
}
else {
obj[x][i]= obj[x][1];
//obj[x] will give you the array belongs to the property x
}
console.log(i+" element of array "+x+" is equal "+ obj[x][i]);
}
}
}
return obj;
}
Operations need to be done obj[x].
Please Check with the code:
var obj = {};
obj.line0 = [0, 0];
obj.line1 = [0, 50];
var pointsLenght = 8;
//things above are just test case sandbox representing small amount of real data
var createPoints = function(obj) {
var i, elem;
for (var x in obj) {
if (obj.hasOwnProperty(x)) {
elem = obj[x];
for (i = 0; i < pointsLenght; i++) {
elem[i] = (i % 2 == 0) ? (i * 50) : elem[1];
console.log(i + " element of array " + elem + " is equal " + elem[i]);
}
}
}
return obj;
}
createPoints(obj);
I have thousands of legacy code that stores array information in a non array.
For example:
container.object1 = someobject;
container.object2 = someotherobject;
container.object3 = anotherone;
What I want to have is:
container.objects[1], container.objects[2], container.objects[3] etc.
The 'object' part of the name is constant. The number part is the position it should be in the array.
How do I do this?
Assuming that object1, object2, etc... are sequential (like an array), then you can just iterate through the container object and find all the sequential objectN properties that exist and add them to an array and stop the loop when one is missing.
container.objects = []; // init empty array
var i = 1;
while (container["object" + i]) {
container.objects.push(container["object" + i]);
i++;
}
If you want the first item object1 to be in the [1] spot instead of the more typical [0] spot in the array, then you need to put an empty object into the array's zeroth slot to start with since your example doesn't have an object0 item.
container.objects = [{}]; // init array with first item empty as an empty object
var i = 1;
while (container["object" + i]) {
container.objects.push(container["object" + i]);
i++;
}
An alternate way to do this is by using keys.
var unsorted = objectwithobjects;
var keys = Object.keys(unsorted);
var items = [];
for (var j=0; j < keys.length; j++) {
items[j] = unsorted[keys[j]];
}
You can add an if-statement to check if a key contains 'object' and only add an element to your entry in that case (if 'objectwithobjects' contains other keys you don't want).
That is pretty easy:
var c = { objects: [] };
for (var o in container) {
var n = o.match(/^object(\d+)$/);
if (n) c.objects[n[1]] = container[o];
}
Now c is your new container object, where c.object[1] == container.object1
I tried doing delete weapons[i]; but even do when I do weapons.length I still get 1. Even though it should be 0. How do I definitely remove an array from weapons[] array?
I comb over the weapons array by doing this:
for (var i = 0, setsLen = weapons.length; i < setsLen; ++i ) {
var searchWeapon = weapons[i].split("|");
// console.log('['+i+'] >> Weapon ID: ' + searchWeapon[0] + ' | Y: ' + searchWeapon[1] + ' | X: ' + searchWeapon[2]);
if (searchWeapon[1] == Y && searchWeapon[2] == X) {
delete weapons[i];
}
}
and I store each array as 3|10|4 where 3 is weapon ID, 10 is Y, and 4 is X.
Check out the .splice method
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice
Using your example:
for (var i = 0, setsLen = weapons.length; i < setsLen; ++i ) {
var searchWeapon = weapons[i].split("|");
if (searchWeapon[1] == Y && searchWeapon[2] == X) {
weapons.splice(i,1);
}
}
Use splice
array.splice(index,howmany)
If your array doesn't need to be sorted, you could use array.pop() as it's extremely fast.
if(index == array.length-1) array.pop();
else array[index] = array.pop();
This method doesn't need to re-index everything after what you've splice()'d, so it remains quick whether your array has a length of 5 or 350,000.
Additional to the answers above:
you should walk the array from the end to the start, otherwise you'll miss elements inside the loop if a item has been removed.
Demo: http://jsfiddle.net/doktormolle/2f9Ye/
deleteing an array element leaves a hole behind with undefined left in the element's place. You probably want to use Array.splice.
var myArray = [1,2,3];
delete myArray[1]; // myArray is now [1, undefined, 3];
var myArray2 = [1,2,3];
myArray2.splice(1,1); // myArray2 is [1, 3]
To remove an element from an array use the splace method. Example:
var myArr = ["apple", "orange", "pear"];
alert(myArr.length); // 3
myArr.splice(1,1); // start at 1th index (i.e 2nd element), remove 1 element
alert(myArr.length); // 2
for (var i=0; i<myArr.length; i++) alert(myArr[i]); // "apple", "pear"
So I have an array. The array has string values inside that can change each time:
var array = ['1','2','3','4','5'];
or sometimes:
var array = ['1','4','3','4','4'];
or even:
var array = ['1','3','3','4','4'];
How would I go about iterating through this array, figuring out which value is present the most and then displaying it. Also, how would I go about making it even smarter to understand that sometimes there is a tie between two values, as is the case in the last array above, and then displaying info notifying me that values "3" and "4" are tied... Or if there is no value that occurs more than once, thus displaying all values. Thoughts?
function findMostFrequent(array) {
// {
// "valueInTheArray": numberOfOccurances,
// ...
// }
var data = {};
// for each value in the array increment the number of
// occurences for that value. the or clause defaults it to 0.
$.each(array, function(i, val) {
data[val] = data[val]++ || 1;
});
var answer = null;
// for each value if the occurances is higher then to the counter.
// then set that as the counter.
$.each(data, function(key, val) {
if (val > data[answer]) answer = key;
}
return answer;
}
You need two loops. One to count how many times each value occured. And one to find which one occured the most.
Optionally if you want to handle multiple high values then replace the second loop with this.
var answer = [null];
// for each value if the occurances is equal then add it to the array
// else if the occurance is higher then the current highest occurance.
// then set that as the current array of values.
$.each(data, function(key, val) {
if (val === data[answer[0]]) {
answer.push(key);
} else if (val > data[answer[0]]) {
answer = [key];
}
}
return answer;
Try this:
var array = ['1','2','3', '3','4','5', '3', '4', '5', '5'],
l = array.length,
col = {},
current,
max = {cnt:0, values:[]};
while(l--){
current = array[l];
col[current] = (col[current] || 0) + 1;
if(col[current] > max.cnt){
max = {cnt:col[current], values: [current]};
}else if(col[current] === max.cnt){
max.values.push(current);
}
}
console.log(
max.cnt === 1 ?
'they are all different' :
max.values.join(',') + ' occured ' + max.cnt + ' times'
);
You probably want to use something like this:
var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
var counts = {};
for(var i = 0; i< arr.length; i++) {
var num = arr[i];
counts[num] = counts[num] ? counts[num]+1 : 1;
}
Now, you'll have an object that has a count of all the members in the array.
console.log(counts[5]); // logs '3'