JavaScript For loop with square brackets - javascript

I understand the basic structure of a For loop in JavaScript. I was looking at the following example:
function howMany(selectObject) {
var numberSelected = 0;
for (var i = 0; i < selectObject.options.length; i++) {
if (selectObject.options[i].selected) {
numberSelected++;
}
}
return numberSelected;
}
On the Fourth line I don't understand what you would call the
[i] in terminology and why it is square brackets?

[] is a way of selecting a property from an object given a specific key, in this case the key (or index) is i and the object is an array. In an array an index can go from 0 to the length of the array - 1.
In an object a key is the name of any property within that object. For example, you can also select the value of the property key selected from the object selectObject.options[i] by using the following: selectedObject.options[i]['selected'].
As an alternative to your for loop, you could use a for in loop. Which works on objects (and arrays).
for (var key in selectObject.options) {
if (selectObject.options[key].selected) {
numberSelected++;
}
}

the [i] is used to address variables in for example an array.
Lets say you have an array names containing sarah and john. names[0] would return sarah.
What your for loop does is go over all the entries in selectObject.options and looks at the value of selected (most likely a true/false).

selectObject.options returns an array, and the [ ], is the way to get an element from the array, using its index (the i in your case)
Say you had an array of strings like so:
var arr = ["this", "is", "an", "array", "of", "strings"];
and you want to access one of the array's elements, you would:
console.log(arr[5]); // prints "strings" to the console

function howMany(selectObject) {
var numberSelected = 0;
for (var i = 0; i < selectObject.options.length; i++) {
if (selectObject.options[i].selected) {
numberSelected++;
}
}
return numberSelected;
}
In this above code why is numberSelected, and in the coditional statement numberSelected++

Related

javascript - search for string in array of objects and return array

I would like to write a function that will search the fields of objects in an array for a specific string, adding this object to a new array if the string is found in any of the object's fields. I've gotten my function to work, but was having the issue of the new list containing multiple copies of the objects which contain multiple copies of the string being searched for. I know this is because I've looped it so that each field it finds the string in, it will add the object once more to the new array. However, I wasn't sure of what alternative way I could go about writing the function to add the object only once, regardless of how many of its fields have matched with the string being searched for. This is my function:
function search (keyword, array){
var newArray = [];
for(let i = 0; i < array.length; i++) {
for (key in array[i]) {
if(array[i][key].includes(keyword)){
newArray.push(array[i]);
}
}
}
return newArray;
}
An example of where the output is problematic is if I do:
console.log(search('yes', myArray))
And if myArray contains an object in which 'yes' appears in 3 different fields, it will add this object to newArray 3 times.
Improved version of Danny Buonocore code.
No accidental global variables.
Uses forEach to iterate over the array.
Uses for...of and Object.values() to iterate over the values of the object (using for..in iterates over all non-Symbol, enumerable properties of an object itself and those the object inherits from its constructor's prototype and are cause for many bugs)
"short circuit" the test for adding an object: if a value has matched, there is no need to check the other values. This alone would probably solved your problem, but using a set will prevent duplicates if you have the same object multiple times in your array.
function search (keyword, array){
var result = new Set();
array.forEach( object => {
for (const value of Object.values(object)) {
if ( value.includes(keyword) ) {
result.add(object);
continue; // Don't need to check more on this item.
}
}
});
return Array.from(result);
}
console.log(search("yes", [
{ key1 :"yes", key2:"yes" },
{ key1 :"no", key2:"no" }
]));
You could use a Set, this will prevent duplicates.
function search (keyword, array){
var result = new Set();
for(let i = 0; i < array.length; i++) {
for (key in array[i]) {
if(array[i][key].includes(keyword)){
result.add(array[i]);
}
}
}
return Array.from(result);
}

Using JavaScript object as an array

function removeDupes() {
var out = [],
obj = {};
for (x = 0; x < intArray.length; x++) {
obj[intArray[x]] = 1;
}
for (x in obj) {
out.push(x);
}
return out;
}
hi all, obj { } is supposed to have been declared as an object, but why putting [ ] and using obj as array works? thanks
someObject["somePropertyName"] is how you access the property of an object. (You can also use someObject.somePropertyName but only if the property name is a valid identifier).
The syntax has nothing specifically to do with arrays.
Arrays are just a type of object with a bunch of methods that treat property names that are integer numbers in special ways.
(Numbers are not valid identifiers so you must use the square bracket syntax to access properties with names that are numbers).
First of all, let's fix your removedDupes function by adding intArray as an argument and declaring the loop iterators as local variables var x:
function removeDupes(intArray) {
var out = [],
obj = {};
for (var x = 0; x < intArray.length; x++) {
obj[intArray[x]] = 1;
}
for (var x in obj) {
out.push(x);
}
return out;
}
The first loop iterates over all intArray elements. For each element it creates a new property on obj with key intArray[x] and value 1 via obj[intArray[x]] = 1. This is called bracket notation. Now, objects can't have duplicate keys. So adding the same property key twice actually overrides the previously added property. Thus, when the loop completes, your obj has exactly one key per unique array element.
The second loop then pushes these keys into the resulting out array.
There are some issues with your removeDupes function. Firstly, it returns an array of string elements even though the input is an array of number elements. This is because obj keys can't be numbers and are always converted to strings. You can fix it by storing the numeric values along with the keys as follows:
function removeDupes(intArray) {
var out = [],
obj = {};
for (var x = 0; x < intArray.length; x++) {
obj[intArray[x]] = intArray[x];
}
for (var x in obj) {
out.push(obj[x]);
}
return out;
}
Now, this works, but it is very verbose. You can make it shorter by replacing the second loop with return Object.values(obj);. Or even shorter by using a Set:
function removeDupes(intArray) {
return [...new Set(intArray)];
}

How to access multidimensional array by index in javascript?

I have an array like below in java-script
Result = [
{"ID":1,"Type":"Pyramid","Phase":"One"},
{"ID":2,"Type":"Pyramid","Phase":"Two"}
]
I tried accessing the individual values and was able to by the below code
alert(Result[0].ID) or alert(Result[0].Phase)
Is there a way to access this by index? like Result[0][1], i tried but getting [object][object]
also i need to access column count
Please help me
You have array of object and by using for loop you can easily access all element value.
try following
function getValue() {
var keys ;
var Result = [{"ID":1,"Type":"Pyramid","Phase":"One"}, {"ID":2,"Type":"Pyramid","Phase":"Two"}]
for(var i=0; i<Result.length;i++){
keys = [];
for(var k in Result[i]){
keys.push(k);
}
for(var k=0;k<keys.length;k++){
console.log(keys[k]+"="+ Result[i][keys[k]]);
}
console.log("key count =" +keys.length);
}
}
CHECK THIS
from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
alert(Result[0][Object.keys(Result[0])[0]]);
Result[0] gets the first row
Object.keys(Result[0]) gets the keys in the first row
Object.keys(Result[0])[0] gets the first column name.
Object.keys(Result[0]).length is the column count in the first row.
Also, objects are not indexed based on a linear integer index as arrays are, so assigning ordered numbers to the unordered list of keys is not right.
A two dimensional array would look like this:
Result = [
[1,"Pyramid","One"],
{2,"Pyramid","Two"}
]
in this case, you could address each field like so: Result[row][col] thus Result[0][2] would yield One.
To access fields in an array of object use the syntax you have provided. Also, why would you want to access the fields in your objects based on id? Or why would you not use an array of arrays?
Your Result is an array of object, then you must first get an object, and then get the property of your object. This is not a multidimensional array.
You array has an object we have to convert that object to array. So converting whole var Result to newResult you can access newResult and it's component through index number
Result = [
{"ID":1,"Type":"Pyramid","Phase":"One"},
{"ID":2,"Type":"Pyramid","Phase":"Two"}
];
var newResult = [];
for (var i = 0; i < Result.length; i++) {
newResult[i] = [];
for (var x in Result[i]) {
if (Result[i].hasOwnProperty(x)) {
newResult[i].push(Result[i][x]);
}
};
};
console.log(newResult);
Use newResult instead of Result
You can get ID by newResult[0][0]
http://jsfiddle.net/LLz1cbok/

Javascript / JQuery - How do I find the size of this array of objects?

I have this code to iterate through an array of objects:
for (vehicleIndex in scenes[sceneID].vehicles) {
vehicleID = scenes[sceneID].vehicles[vehicleIndex];
...
}
but I need to know how to determine the number of items being iterated through so that on the final item, I can execute a particular function. How do I do this?
Example in ES5:
Object.keys( scenes[sceneID].vehicles ).forEach(function( vehicle, index, arr ) {
if( index === arr.length - 1 ) {
// do something on last entry
}
});
Even tho, "last" just means the last element which was looped over. Since there is specific order within a Javascript object (they are infact unordered). However, we could sort the object key names manually by just chaining a .sort() before the .forEach()
var arraySize = scenes[sceneID].vehicles.length;
var i;
var currentItem;
for (i = 0; i < arraySize; i++) {
currentItem = scenes[sceneID].vehicles[i];
if (i == arraySize - 1) {
// do something special
} else {
// do something not so special ;-)
}
}
scenes[sceneID].vehicles should have a length property.
for (vehicleIndex in scenes[sceneID].vehicles) {
vehicleID = scenes[sceneID].vehicles[vehicleIndex];
...
}
doSomethingWithLastItem(vehicleId);
Because JS does not have block scope, by the time your loop finished vehicleId will be the last item's id.
In generic terms you can get the size of an array by accessing the .length property. You can also get the size of an object using Object.keys(obj).length.
Use this to find the length:
scenes[sceneID].vehicles.length
length is a built-in property in arrays. However, if you want to check for the last item, you have to check
scenes[sceneID].vehicles.length - 1
as arrays are zero-indexed.
Also, you should not use for...in to loop on arrays - if someone extends Array.prototype (or worse, Object.prototype), then you will not be happy. Use a normal for loop (which also allows you to use the final item easily):
var len = scenes[sceneID].vehicles.length;
for (var vehicleIndex = 0; vehicleIndex < len; vehicleIndex++) {
vehicleID = scenes[sceneID].vehicles[vehicleIndex];
//...
}
//Do something with the final item here
//Similar to this: itemFunc(vehicleID);
See this SO question for more details.

JavaScript Array

I usually script/program using python but have recently begun programming with JavaScript and have run into some problems while working with arrays.
In python, when I create an array and use for x in y I get this:
myarray = [5,4,3,2,1]
for x in myarray:
print x
and I get the expected output of:
5
4
3
..n
But my problem is that when using Javascript I get a different and completely unexpected (to me) result:
var world = [5,4,3,2,1]
for (var num in world) {
alert(num);
}
and I get the result:
0
1
2
..n
How can I get JavaScript to output num as the value in the array like python and why is this happening?
JavaScript and Python are different, and you do things in different ways between them.
In JavaScript, you really should (almost) always iterate over an array with a numeric index:
for (var i = 0; i < array.length; ++i)
alert(array[i]);
The "for ... in" construct in JavaScript gives you the keys of the object, not the values. It's tricky to use on an array because it operates on the array as an object, treating it no differently than any other sort of object. Thus, if the array object has additional properties — which is completely "legal" and not uncommon — your loop will pick those up in addition to the indexes of the "normal" array contents.
The variable num contains the array item's index, not the value. So you'd want:
alert(world[num])
to retrieve the value
The for var in... loop in JavaScript puts the keys in the variable instead of the actual value. So when using for var ... you should do something like this:
var world = [5, 4, 3, 2, 1];
for ( var key in world ) {
var value = world[key];
alert(key + " = " + value);
}
And note that this way of looping is best used when you're using objects instead of arrays. For arrays use the common:
for ( var i = 0, j = arr.length; i < j; i++ ) { ... }
Or if you're targeting modern browser you can use the forEach-method of arrays:
var arr = [1, 2, 3];
arr.forEach(function(num) {
alert(num);
});
The for...in loop loops over all key elements; not the values.
I would recommend you to use
for(var i=0; i<arr.length; i++){
alert(arr[i]);
}
When you use the in operator num becomes a key. So simply use this key to get a value out of the array.
var world = [5,4,3,2,1]
for (var num in world) {
alert(world[num]);
}
try this.
var world = [5,4,3,2,1]
for(var i=0;i<world.length;i++){
alert(world[i])
}
Because javascript in your case is printing the index of the element, not the value.
the result you got is just element index,if you want to get element value
your code should like this
var world = [5,4,3,2,1]
for (var num in world) {
alert(world[num]);
}
The for in iteration in JavaScript works only for the object data type. The way it works is that it lets you iterate over the attributes of an object. arrays are objects in JavaScript, but the for in only works on its attributes, not the array values.
For example you might define an array as such:
var arr = [1,2,3];
And you can assign attributes to this array, because it's actually an object:
arr.foo = "bar";
arr["1"] = 2;
Now when you use the for in iteration method you will be able to iterate over the attributes we just assigned above;
for(var i in arr) console.log(i);
To iterate over the actual array values you need to use the for(var i=0; i<arr.length; i++) construct.
Hope this helps.
In javascript it's advised to loop Arrays different from looping Objects. You are using an object loop, which may return unexpected result (for instance if the Array.prototype was extended with custom methods you would iterate those too, and it does't guarantee the order of the array is preserved). There are many ways to loop through an array, using it's index:
// regular
var arr = [1,2,3,4,5]
,i
;
for (i=0;i<arr.length;i++) {
console.log(arr[i]);
}
// using while
var arr = [1,2,3,4,5]
,i = 0
;
while ((i = i + 1)<arr.length) {
console.log(arr[i]);
}
// using while reversed
var arr = [1,2,3,4,5]
,i = arr.length
;
while ((i = i - 1) > -1) {
console.log(arr[i]);
}
Note: Why not use i++ or i--? To avoid confusion, index out of range-errors and to satisfy JSLint

Categories