Google News
logo
Underscore.js - Interview Questions
What are the Iterating Arrays in Underscore.js?
first _.first(array, [n]) Aliases : head, take
Returns the first element of an array. Passing n will return the first n elements of the array.
_.first([5, 4, 3, 2, 1]);
=> 5
initial _.initial(array, [n])
Returns everything but the last entry of the array. Especially useful on the arguments object. Pass n to exclude the last n elements from the result.
_.initial([5, 4, 3, 2, 1]);
=> [5, 4, 3, 2]
last _.last(array, [n])
Returns the last element of an array. Passing n will return the last n elements of the array.
_.last([5, 4, 3, 2, 1]);
=> 1
rest _.rest(array, [index]) Aliases : tail, drop
Returns the rest of the elements in an array. Pass an index to return the values of the array from that index onward.
_.rest([5, 4, 3, 2, 1]);
=> [4, 3, 2, 1]
 
indexOf _.indexOf(array, value, [isSorted])
Returns the index at which value can be found in the array, or -1 if value is not present in the array. If you're working with a large array, and you know that the array is already sorted, pass true for isSorted to use a faster binary search ... or, pass a number as the third argument in order to look for the first matching value in the array after the given index. If isSorted is true, this function uses operator < (note).
_.indexOf([1, 2, 3], 2);
=> 1
lastIndexOf _.lastIndexOf(array, value, [fromIndex])
Returns the index of the last occurrence of value in the array, or -1 if value is not present. Pass fromIndex to start your search at a given index.
_.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
=> 4
sortedIndex _.sortedIndex(array, value, [iteratee], [context])
Uses a binary search to determine the smallest index at which the value should be inserted into the array in order to maintain the array's sorted order. If an iteratee function is provided, it will be used to compute the sort ranking of each value, including the value you pass. The iteratee may also be the string name of the property to sort by (eg. length). This function uses operator < (note).
_.sortedIndex([10, 20, 30, 40, 50], 35);
=> 3

var stooges = [{name: 'moe', age: 40}, {name: 'curly', age: 60}];
_.sortedIndex(stooges, {name: 'larry', age: 50}, 'age');
=> 1
 
findIndex _.findIndex(array, predicate, [context])
Similar to _.indexOf, returns the first index where the predicate truth test passes; otherwise returns -1.
_.findIndex([4, 6, 8, 12], isPrime);
=> -1 // not found
_.findIndex([4, 6, 7, 12], isPrime);
=> 2
findLastIndex _.findLastIndex(array, predicate, [context])
Like _.findIndex but iterates the array in reverse, returning the index closest to the end where the predicate truth test passes.
var users = [{'id': 1, 'name': 'Bob', 'last': 'Brown'},
             {'id': 2, 'name': 'Ted', 'last': 'White'},
             {'id': 3, 'name': 'Frank', 'last': 'James'},
             {'id': 4, 'name': 'Ted', 'last': 'Jones'}];
_.findLastIndex(users, {
  name: 'Ted'
});
=> 3
Advertisement