loop through array in ES5

If you’re using an environment that supports the Array features of ES5 (directly or using a shim), you can use the new forEach function:

var a = ["a", "b", "c"];
a.forEach(function(entry) {
    console.log(entry);
});

forEach accepts an iterator function and, optionally, a value to use as this when calling that iterator function (not used above). The iterator function is called for each entry in the array, in order, skipping non-existent entries in sparse arrays. Although I only used one argument above, the iterator function is called with three: The value of each entry, the index of that entry, and a reference to the array you’re iterating over (in case your function doesn’t already have it handy).

Using forEach on a general-purpose web page still (as of March 2014) requires that you include a “shim” for it for browsers that don’t support it natively, because IE8 and earlier don’t have it (and they’re used by somewhere between 7% and 21% of the global browser users depending on who you believe; that figure is skewed a bit by markedly higher use in China vs. elsewhere, always check your own stats to see what you need to support). But shimming/polyfilling it is easily done (search for “es5 shim” for several options).

forEach has the benefit that you don’t have to declare indexing and value variables in the containing scope, as they’re supplied as arguments to the iteration function, and so nicely scoped to just that iteration.

If you’re worried about the runtime cost of making a function call for each array entry, don’t be; details.

Additionally, forEach is the “loop through them all” function, but ES5 defined several other useful “work your way through the array and do things” functions, including:

  • every stops looping the first time the iterator returns false or something falsey)
  • some (stops looping the first time the iterator returns true or something truthy)
  • filter (creates a new array including elements where the filter function returns true and omitting the ones where it returns false)
  • map (creates a new array from the values returned by the iterator function)
  • reduce (builds up a value by repeated calling the iterator, passing in previous values; see the spec for the details; useful for summing the contents of an array and many other things)
    • like to Return an array consisting of the largest number from each provided sub-array.
      function largestOf2dArray(arr) {
        return arr.map(function(subArray){
          return subArray.reduce(function(previousValue, currentValue){
             return previousValue > currentValue ? previousValue: currentValue;
          });
        });
      }
      
  • reduceRight (like reduce, but works in descending rather than ascending order)

angularjs filter on array

Use property in input’s ng model

Filter is used for selecting a subset of a give array. The requirements for a filter are an array to be filtered and the predicate based on which the array need to be filtered. The predicate could be as simple as a string and let’s try filtering using a string at first.

<div class="container" style="margin-top:100px;">
    <div class="row">
        <div class="span12" ng-controller="MediaCtrl">
            <input type="text" ng-model="searchTerm">
            <table class="table">
                <thead>
                    <tr>
<th><a href="" ng-click="setSortExpression('artistName')" >Artist Name</a></th>
<th><a href="" ng-click="setSortExpression('trackName')">Track</a></th>
<th><a href="" ng-click="setSortExpression('primaryGenreName')">Genre</a></th>
<th><a href="" ng-click="setSortExpression('trackPrice')" >Price</a></th>                       
                    </tr>
                </thead>
                <tbody>
<tr ng-repeat="r in result.results | filter:searchTerm  | orderBy:sortExpression">
    <td>{{r.artistName}}</td>
    <td>{{r.trackName}}</td>
    <td>{{r.primaryGenreName}}</td>
    <td>{{r.trackPrice}}</td>
</tr>
                </tbody>
            </table>


        </div>
    </div>
</div>

Giving a full blown filtering to our application is as easy as introduing a new model (searchTerm here) and applying the filter to the array model passing the model value as argument. The drawback (or advantage) of this method is it matches the records based on comparing the search term with each and every property of the objects in the array. If we need to fine tune the filtering process we can pass an object instead of a simple string.

<div class="container" style="margin-top:100px;">
    <div class="row">
        <div class="span12" ng-controller="MediaCtrl">
            <input type="text" ng-model="searchTerm.$">
            <table class="table">
                <thead>
                    <tr>
<th><a href="" ng-click="setSortExpression('artistName')" >Artist Name</a>
    <br><input type="text" ng-model="searchTerm.artistName">
</th>
<th><a href="" ng-click="setSortExpression('trackName')">Track</a>
    <br><input type="text" ng-model="searchTerm.trackName"></th>
<th><a href="" ng-click="setSortExpression('primaryGenreName')">Genre</a>
    <br><input type="text" ng-model="searchTerm.primaryGenreName"></th>
<th><a href="" ng-click="setSortExpression('trackPrice')" >Price</a>
    <br><input type="text" ng-model="searchTerm.trackPrice"></th>                       
                    </tr>
                </thead>
                <tbody>
<tr ng-repeat="r in result.results | filter:searchTerm  | orderBy:sortExpression">
    <td>{{r.artistName}}</td>
    <td>{{r.trackName}}</td>
    <td>{{r.primaryGenreName}}</td>
    <td>{{r.trackPrice}}</td>
</tr>
                </tbody>
            </table>


        </div>
    </div>
</div>

Now the search tern is an object with properties matching those on the listed columns and the list is filtered based on the values inside this object. Dollar ($) symbol has a special meaning of match all the properties and it is used for searching across all of the properties.

Use function

Another way to do this is to use a function:

<div ng-repeat="product in products | filter: myFilter">

$scope.myFilter = function (item) { 
    return item === 'red' || item === 'blue'; 
};

Use object structure in filter expression

If you want to filter on a grandchild (or deeper) of the given object, you can continue to build out your object hierarchy. For example, if you want to filter on ‘thing.properties.title’, you can do the following:

<div ng-repeat="thing in things | filter: { properties: { title: title_filter } }">

You can also filter on multiple properties of an object just by adding them to your filter object:

<div ng-repeat="thing in things | filter: { properties: { title: title_filter, id: id_filter } }">

Be careful with angular filter

If you want select specific value in field, you can’t use filter.

Example:

app.controller('FooCtrl', function($scope) {
   $scope.products = [
       { id: 1, name: 'test', color: 'lightblue' },
       { id: 2, name: 'bob', color: 'blue' }
       /*... etc... */
   ];
});

<div ng-repeat="product in products | filter: { color: 'blue' }"> 

This will select both, because use something like substr
That means you want select product where “color” contains string “blue” and not where “color” is “blue”.

<div ng-repeat="product in products | filter: { color: 'blue' }:true">

will work on only exact matches (the ‘true’ at the end is the comparator argument: link

from here

reduce function for array in javascript

Parameters

callback
Function to execute on each value in the array, taking four arguments:

previousValue
The value previously returned in the last invocation of the callback, or initialValue, if supplied. (See below.)
currentValue
The current element being processed in the array.
index
The index of the current element being processed in the array.
array
The array reduce was called upon.
initialValue
Optional. Object to use as the first argument to the first call of the callback.
[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, index, array) {
  return previousValue + currentValue;
}, 10);

Examples

 Example: Flatten an array of arrays

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
  return a.concat(b);
});
// flattened is [0, 1, 2, 3, 4, 5]

 

Consider the case of a library system which needs to show potential donors its effectiveness at spreading knowledge. In order to do that, it must determine how many book-checkouts there were last year. (Not total of all checkouts, since a single checkout may be for more than one book.)

Their data is stored in an object like this:

var books = [
    {
        title: "Showings",
        author: "Julian of Norwich",
        checkouts: 45
    },
    {
        title: "The Triads",
        author: "Gregory Palamas",
        checkouts: 32
    },
    {
        title: "The Praktikos",
        author: "Evagrius Ponticus",
        checkouts: 29
    }
];

The traditional C-style way to get at that number would be something like this:

var bookCheckouts = 0;

for (var i = 0; i < books.length; i++) {
    bookCheckouts = bookCheckouts + books[i].checkouts;
}

But using reduce, we can think more directly about the problem itself:

// Get an array of checkout values only
var bookCheckouts = books.map(function(item) {
    return item.checkouts;
});

// Sum the array's values from left to right
var total = bookCheckouts.reduce(function(prev, curr) {
    return prev + curr;
});

While it may look a little foreign at first, this example is more explicit about the problem than thefor version is. Namely, dealing only with the checkouts property, and totaling them. And if you are familiar with the idioms, you can make it almost as concise.

// Get total of book checkouts
var total = books
            .map(function(b) { return b.checkouts; })
            .reduce(function(p, c) { return p + c; });

So how does that reduce method work? It takes an array of values and executes the function (almost!) once for each item in the array. The value of prev is the result of the calculations up to this point. Let’s take a look:

[1, 2, 3].reduce(function(prev, curr, index) {
    console.log(prev, curr, index);
    return prev + curr;
});

// Outputs:
// 1, 2, 1
// 3, 3, 2
// 6

As you can see, the callback actually didn’t iterate over the first element of the array. Instead,prev was set to the value of the first element. It has to work that way because otherwisereduce wouldn’t have a starting value for prev.

The function ran three times, but on the last call, it wasn’t given a current element since there were no elements left in the array. That behavior is a little confusing to read through, but is quite easy to use.

Here is another example:

[1, 2, 3].reduce(function(prev, curr, index) {
    console.log(prev, curr, index);
    return prev + curr;
}, 100);

// Outputs:
// 100 1 0
// 101 2 1
// 103 3 2
// 106

In addition to the callback function, we also passed in an initial value for prev. You’ll note that in this case, the callback did iterate over the first element in the array, since it had an initial value to work with.

It should be noted that your callback function also has access to the array itself as a parameter.

[1, 2, 3].reduce(function(prev, curr, index, arr) {
    // Do something here
});

Is reduce only good for working with numbers? By no means. Consider this:

var relArray = [
    ["Viola", "Orsino"],
    ["Orsino", "Olivia"],
    ["Olivia", "Cesario"]
];

var relMap = relArray.reduce(function(memo, curr) {
    memo[curr[0]] = curr[1];
    return memo;
}, {});

// Outputs: {
//    "Viola": "Orsino",
//    "Orsino": "Olivia",
//    "Olivia": "Cesario"
// }
console.log(relMap);

This time we used reduce to transform the relationship data from an array of arrays into an object where each key value pair describes the relationship. You’ll also see that instead of naming the parameter prev as I did before, I used the term memo. That’s because in this case, memo is a more descriptive name for the actual value being passed in (an object collecting new properties.)

The reduce method is good for any sort of situation where we want to take an array and boil it down into a new value in steps that have access to one or two of the array elements at a time.

Want to use reduce in IE8 or IE7? Take a look at the Underscore and Lo-Dash libraries.

 

FROM HERE

javascript array in depth

What is an Array in JavaScript?

A numerically indexed map of values.

Traditionally an array reserves a continuous allocation of memory of predefined length. In JavaScript this is not the case. A JavaScript array is simply a glorified object with a unique constructor and literal syntax and an additional set of properties and methods inherited from Array.prototype. If this means we make a small sacrifice in performance, it is more than compensated for by its ease of use and the power of its utilities. Unlike its counterparts in certain other languages, JavaScript arrays are a joy to use – this is something they definitely got right.

How do I create a JavaScript Array?

Lets start with the best way. In JavaScript, whenever there is a literal syntax for object creation it generally makes sense to use it.

1
2
3
4
5
6
7
8
9
10
11
//create a new, empty array
var a = [];
//add members to an existing array
a[0] = "Bob";
a[1] = "Mary";
a[2] = "Joe";
//or simply use push
a.push("Jane");
a.push("Carlos");
//create a new array and predefine some members
var b = ["Bob", "Mary", "Joe", "Jane", "Carlos"];

Alternatively you could use the new Constructor syntax. Apart from the obvious drawback of 5-9 additional assaults on your dainty finger pads (the “new” part is effectively optional) there is a more serious issue around ambiguity of intention:

1
2
3
4
5
6
7
8
//create a new array with 8 undefined members
var a = new Array(8);
//create a new array containing two predefined elements
var b = new Array(8,9);
a.length; //8
b.length; //2
a[0]; //undefined
b[0]; //8

These two declarations look strikingly similar yet produce entirely different results. Moreover, lets say someone edits the second statement because they now only want to predefine one element, the number 8, in array b. It’s quite likely they might modify it to the following (and who could blame them?):

1
2
//create a new array containing one predefined element
var b = new Array(8); //Wrong!

Of course this doesn’t do what they wanted. The only way to predefine an array with one primitive number is to use the literal syntax. (Thanks Peter and Dmitry for clarification)

Is there any advantage to using the new Array syntax?

Well it means you can define the length of your array at creation time. But since JavaScript arrays do not require an up front allocation of memory, and they can be lengthened at will any time, that’s a questionable requirement. (Several people pointed out webkit et al have built in optimization when Array length predefined – though there is nothing in the spec to suggest this)

What types of data can an Array contain?

An array can contain any object or primitive type. Multiple data types can co-exist in the same array.

How do I access an Array element?

Array elements are simply object properties and are accessed in the same way as other object properties. Since property identifiers are always strings, the array index is also a string, not a number. However when you use subscript notation (square brackets) to access the property, a number literal can also be used since it will be coerced to a string by the interpreter. Dot notation accessors will not work for array member access because literal property identifiers can’t start with a number (again, all these behaviours derive from generic object property rules, they are not array-specific)

1
2
3
var a = ["banana", Math.min, 4, "apple"];
a['1']; //min()
a[2]; //4

How should I iterate over the elements of an array?

Typically it makes sense to use the standard for loop:

1
2
3
4
var a = ["banana", Math.min, 4, "apple"];
for (var i=0; i < a.length; i++) {
    console.log(a[i]);
}

If your array is a long one you may be worried about the additional cost of requesting array.length on every iteration. To workaround this you can define the array length up front:

1
2
3
4
5
var a = makeBigArray();
for (var i=0,  aLength = a.length; i < aLength; i++) {
    console.log(a[i]);
}

Using a for…in statement for array iteration is not advised because you may also pick up enumerable properties from the prototype (see below)

Which properties are unique to Arrays?

The most important array property is length (strings and functions have length too but the array definition of length is unique)

Array.length is NOT a read-only value, you can set it as you wish.

ECMA specifies:
The length property of this Array object is always numerically greater than the name of every property whose name is an array index

In other words its (the numeric value of the last index) + 1

Array’s are not upper-bound. You can add an element at an index greater than (length – 1) and the length property will be modified based on the above definition. Array’s have a maximum length but its too big for you to worry about.

1
2
3
4
5
6
var a = [3,4,1];
a.length; //3
a[20] = 2;
a.length; //21
//element indexes 3-19 automatically created with value initialized to undefined
a[18]; //undefined

Arrays are lower-bound to zero. If you try to add a value at a negative index you will just be writing a regular object property (see also “associative arrays” below)

1
2
3
4
5
var a = [];
a[-1] = "giraffe";
a[-1]; //"giraffe"; //because still using a regular object property accessor
a.length; //0
a.toString(); //""

You can manipulate the contents of an existing array by updating its length value. If you reduce the length property of an existing array, members with indexes greater than or equal to the new length get discarded (this turns out to be the only way to remove indexes from an array – you can delete an element but this will only delete the value and leave the index in place – i.e. your array becomes “sparse” = it gets holes in it)

1
2
3
4
5
var a = [0,1,2,3,4,5,6];
a.length; //7
a.length = 5;
a.toString(); //"0,1,2,3,4"
a[6]; //undefined

Conversely if you increase the length of an existing array by n your array appears to get n new members, each with its value initialized to undefined – however as Dmitry Soshnikov points out, this is the standard response to accessing a non existent property. In reality nothing has changed except the array length.

1
2
3
4
5
6
7
8
var a = [0,1,2,3,4,5,6];
a.length; //7
a[9]; //undefined
a[59]; //undefined
a.length = 10;
a.toString(); //"0,1,2,3,4,5,6,,,"
a[9]; //undefined
a[59]; //undefined

There are two additional pseudo-properties of arrays: index and input. These properties are only present in arrays created by regular expression matches

 

java vs c++

At the beginning of a new project, you may be faced with the question, “Should I use C++ (or some other language) for my next project, or should I use Java?” As an implementation language, Java has some advantages and some disadvantages over other languages. One of the most compelling reasons for using Java as a language is that it can enhance developer productivity. The main disadvantage is potentially slower execution speed.

Java is, first and foremost, an object-oriented language. One promise of object-orientation is that it promotes the re-use of code, resulting in better productivity for developers. This may make Java more attractive than a procedural language such as C, but doesn’t add much value to Java over C++. Yet compared to C++, Java has some significant differences that can improve a developer’s productivity. This productivity boost comes mostly from Java’s restrictions on direct memory manipulation.

In Java, there is no way to directly access memory by arbitrarily casting pointers to a different type or by using pointer arithmetic, as there is in C++. Java requires that you strictly obey rules of type when working with objects. If you have a reference (similar to a pointer in C++) to an object of type Mountain, you can only manipulate it as a Mountain. You can’t cast the reference to type Lava and manipulate the memory as if it were a Lava. Neither can you simply add an arbitrary offset to the reference, as pointer arithmetic allows you to do in C++. You can, in Java, cast a reference to a different type, but only if the object really is of the new type. For example, if the Mountain reference actually referred to an instance of class Volcano (a specialized type of Mountain), you could cast the Mountain reference to a Volcano reference. Because Java enforces strict type rules at run- time, you are not able to directly manipulate memory in ways that can accidentally corrupt it. As a result, you can’t ever create certain kinds of bugs in Java programs that regularly harass C++ programmers and hamper their productivity.

Another way Java prevents you from inadvertently corrupting memory is through automatic garbage collection. Java has a new operator, just like C++, that you use to allocate memory on the heap for a new object. But unlike C++, Java has no corresponding delete operator, which C++ programmers use to free the memory for an object that is no longer needed by the program. In Java, you merely stop referencing an object, and at some later time, the garbage collector will reclaim the memory occupied by the object.

The garbage collector prevents Java programmers from needing to explicitly indicate which objects should be freed. As a C++ project grows in size and complexity, it often becomes increasingly difficult for programmers to determine when an object should be freed, or even whether an object has already been freed. This results in memory leaks, in which unused objects are never freed, and memory corruption, in which the same object is accidentally freed multiple times. Both kinds of memory troubles cause C++ programs to crash, but in ways that make it difficult to track down the exact source of the problem. You can be more productive in Java primarily because you don’t have to chase down memory corruption bugs. But also, you can be more productive because when you no longer have to worry about explicitly freeing memory, program design becomes easier.

A third way Java protects the integrity of memory at run-time is array bounds checking. In C++, arrays are really shorthand for pointer arithmetic, which brings with it the potential for memory corruption. C++ allows you to declare an array of ten items, then write to the eleventh item, even though that tramples on memory. In Java, arrays are full-fledged objects, and array bounds are checked each time an array is used. If you create an array of ten items in Java and try to write to the eleventh, Java will throw an exception. Java won’t let you corrupt memory by writing beyond the end of an array.

One final example of how Java ensures program robustness is by checking object references, each time they are used, to make sure they are not null. In C++, using a null pointer usually results in a program crash. In Java, using a null reference results in an exception being thrown.

FROM HERE