Javascript array higher-order functions - javascript

Can anyone explain to me how this code works? I looked for reduce and concat functions in Array, I understand these functions but I don't understand how this code works initialy:
var arrays = [[1, 2, 3], [4, 5], [6]];
console.log(arrays.reduce(function(flat, current) {
return flat.concat(current);
}, []));
// → [1, 2, 3, 4, 5, 6]

Well actually it's a wrong use of .reduce(). For this job you don't need no initial array. Just the previous (p) and current (c) hand to hand can do it. Such as;
var arrays = [[1, 2, 3], [4, 5], [6]];
console.log(arrays.reduce((p,c) => p.concat(c)));
Note: Initial is handy when the type of the returned value is different from the array items. However in this case you are processing arrays and returning an array which renders the use of initial redundant.

I've described each step for you.
var arrays = [[1, 2, 3], [4, 5], [6]];
console.log(arrays.reduce(function(flat, current) {
// first loop: flat - [1,2,3], current - [4,5]
// [1,2,3].concat([4,5]) -> [1,2,3,4,5]
//second/last loop: flat - [1,2,3,4,5], current - [6]
// [1,2,3,4,5].concat([6]) -> [1,2,3,4,5,6]
//function stop
return flat.concat(current);
}, []));

You could add a console.log inside the callback we pass to the reduce and think about the output:
var arrays = [[1, 2, 3], [4, 5], [6]];
console.log(arrays.reduce(function(flat, current) {
console.log('flat: '+ flat + 'current: ' + current)
return flat.concat(current);
}, []));
Initially we concat an empty array and the array [1,2,3]. So the result is a new array with elements [1,2,3]. Then we concat this array with the next element of the arrays, the array [4,5]. So the result would be a new array with elements [1,2,3,4,5]. Last we concat this array with the last element of the arrays, the array [6]. Hence the result is the array [1,2,3,4,5,6].
Ir order to understand in details the above you have to read about Array.prototype.reduce().
As it is stated in the above link:
The reduce() method applies a function against an accumulator and each
value of the array (from left-to-right) to reduce it to a single value
Furthermore the syntax is
arr.reduce(callback, [initialValue])
In you case the initialValue is an empty array, [].

So assuming we have the 2D array that you do: [[1, 2, 3], [4, 5], [6]] that is being reduced, the function is split into 2 main components.
array.reduce((accumulator, iterator) => {...}, initialValue);
flat - this is the accumulator of the reduction. It is given the initial value as passed into the second parameter of the reduce function and is used to store the values as the iterator passes through them.
current - this is the iterator that goes through all values within the data set being reduced.
So as you're iterating through the data set, your example is concatenating the accumulation array with the current value, and by the end you have your new array.

Array.reduce expects a callback with following signature:
function(previousElement, currentElement, index, array)
and an optional initial value.
In first iteration, if initialValue is passed, then previousElement will hold this value and currentElement will hold `firstArrayElement.
If not, then previousElement will hold firstArrayElement and currentElement will hold secondArrayElement.
For the following iterations, previousElement will hold value returned by previous iteration and currentElement will hold next value.
So in you example, initially flat holds [].
return flat.concat(current); will return a new merged array. This value will be used as flat for next iteration, and this process is returned. Finally, value returned by last iteration is used as final return value and is printed in console.

Related

map() method mutating the calling Array

map() can't mutate the calling array, instead it returns a new Array with modified values.
But, the following code mutating the original Array, is there any wrong in my understanding?
const arr = [1, 2, 3, 4, 5];
arr.map((num, index, arr1) => {
return arr1[index] = num * 2;
});
console.log(arr); // [2, 4, 6, 8, 10]
Well, you're mutating the original array by passing its reference into the callback function inside map() (arr1) and then manually accessing the indices. It will create a new array if you just return the value from that function.
const arr = [1, 2, 3, 4, 5];
const arr1 = arr.map((num) => {
return num * 2;
});
console.log(arr); // [1, 2, 3, 4, 5]
console.log(arr1); // [2, 4, 6, 8, 10]
The third argument to the callback function of map is the
original/source array on which the map is called upon
The arr and arr1 are both same i.e both are referencing on the same array, You can see it by using console.log(arr === arr1). So what ever you operation perform on the arr1, it gonna affect the arr.
const arr = [1, 2, 3, 4, 5];
arr.map((num, index, arr1) => {
console.log(arr1 === arr);
return num * 2;
});
You can just return num * 2 from the callback function. map internally creates a new array and return it. So you don't have to assign it as
arr1[index] = num * 2
You can also make it one-liner as:
arr.map((num, index, arr1) => num * 2)
const arr = [1, 2, 3, 4, 5];
const result = arr.map((num, index, arr1) => {
return num * 2;
});
console.log(arr); // [2, 4, 6, 8, 10]
console.log(result); // [2, 4, 6, 8, 10]
Array.map creates a new array populated with the results of calling a provided function on every element in the calling array.
Here its specifed that you must call or execute a function on every element of calling array.
What is the issue with your code?
You are not actually calling a function, you are instead updating the original array. If you are looking to create a new array by multiplying each node of the element with 2, you should do something like below.
Working Example
const arr = [1, 2, 3, 4, 5];
const newArray = arr.map((nodeFromOriginalArray, indexOfCurrentElement, arrayFromMapCalled) => {
return nodeFromOriginalArray * 2;
});
console.log(arr);
console.log(newArray);
Lets debug the paremeters inside the map function.
Here we have provided three arguments.
First argument nodeFromOriginalArray: The current element being processed in the array. This will be each node from your calling array.
Second argument indexOfCurrentElement: The index of the current element being processed in the array. Which means, the index of current element in calling array.
Third argument arrayFromMapCalled: The array map was called upon. This is the array on which the map function is getting executed. Please note, this is the original array. Updating properties inside this array results in updating your calling array. This is what happened in your case.
You should not modify your original array, which is the third parameter. Instead, you should return your node multipled by 2 inside map and assign this to a new array. Updating the third paramater inside the map function will mutate your calling array.
When calling map on an array, you provide a mapper with three arguments, an item in the array, it's index and the array itself (as you've represented in your snippet).
map takes the value returned by the function mapper as the element at the index in a new array returned by the operation.
const arr = [1,2,3,4,5]
const doubled = arr.map(x => x * 2) // [2,4,6,8, 10]
A over simplified implementation of map (without the index and originalArray params) might look like this. Let's assume that instead of being a method on the array instance, it's a function that takes an array and a mapper function.
I would not recommend re-implementing in production code, there's the native implementation as well as several libraries such as lodash and underscore that implement it.
function map(arr, mapper) {
const result = [];
for (const item of arr) {
const resultItem = mapper(item);
result.push(resultItem);
}
return result;
}
function double(x) {
return x * 2;
}
const doubled = map([1,2,3,4,5,6], double); // [2, 4, 6, 8 ,10, 12]

Check if an array includes an array in javascript

The javascript includes function can be used to find if an element is present in an array. Take the following example:
var arr = ['hello', 2, 4, [1, 2]];
console.log( arr.includes('hello') );
console.log( arr.includes(2) );
console.log( arr.includes(3) );
console.log( arr.includes([1, 2]) );
Passing 'hello' or 2 to the function returns true, as both are present in the array arr.
Passing 3 to the function returns false because it is not present in the array.
However, why does arr.includes([1, 2]) return false as well, even though this is equal to the last element in the array? And if this method does not work, how else can I find whether my array includes the item [1, 2]?
.includes() method uses sameValueZero equality algorithm to determine whether an element is present in an array or not.
When the two values being compared are not numbers, sameValueZero algorithm uses SameValueNonNumber algorithm. This algorithm consists of 8 steps and the last step is relevant to your code , i.e. when comparison is made between two objects. This step is:
Return true if x and y are the same Object value. Otherwise, return false.
So in case of objects, SameValueZero algorithm returns true only if the two objects are same.
In your code, since the array [1, 2] inside arr array is identically different to [1, 2] that you passed to .includes() method, .includes() method can't find the array inside arr and as a result returns false.
The Array#includes checks by shallow comparison, so in your case the string and numbers are primitives there is only ever a single instance of them so you get true from Array#includes.
But when you check for array, you are passing a new array instance which is not the same instance in the array you are checking so shallow comparison fails.
To check for an array is included in another array first check if it is an array then do a deep comparison between the arrays.
Note that below snippet only works for an array of primitives:
var arr = ['hello', 2, 4, [1, 2]];
const includesArray = (data, arr) => {
return data.some(e => Array.isArray(e) && e.every((o, i) => Object.is(arr[i], o)));
}
console.log(includesArray(arr, [1, 2]));
But if you keep the reference to the array [1, 2] and search with the reference the Array#includes works as in this case the shallow comparison works perfectly (obeying same value zero algorithm):
const child = [1, 2];
const arr = ['hello', 2, 4, child];
console.log(arr.includes(child));
If you don't mind using lodash, this algorithm is accurate - unlike the accepted answer.
import _ from 'lodash';
export const includesArray = (haystack, needle) => {
for (let arr of haystack)
if (_.isEqual(arr, needle)) {
return true
}
return false
}

Using Difference from Lodash

I'm trying to set a new state for my react project and I'm stuck on what I'm doing wrong.I want to get the difference of 2 integer arrays
const results = _.difference(items, currSelection);
this.setState({ selected: results });
currSelection is:
[1, 2, 3, 7]
item is:
[1]
when I console.log results, I always get
[]
Reverse the arguments as shown below:
const currSelection = [1, 2, 3, 7];
const items = [1];
const results = _.difference(currSelection, items);
console.log(results); //[2, 3, 7]
_.difference(array, [values])
Creates an array of array values not included in the other given arrays >using SameValueZero for equality comparisons. The order of result values >is determined by the order they occur in the first array.
Arguments
array (Array): The array to inspect.
[values] (...Array): The values to exclude.
Returns
(Array): Returns the new array of filtered values.

JavaScript Array splice vs slice

What is the difference between splice and slice ?
const array = [1, 2, 3, 4, 5];
array.splice(index, 1);
array.slice(index, 1);
splice() changes the original array whereas slice() doesn't but both of them returns array object.
See the examples below:
var array=[1,2,3,4,5];
console.log(array.splice(2));
This will return [3,4,5]. The original array is affected resulting in array being [1,2].
var array=[1,2,3,4,5]
console.log(array.slice(2));
This will return [3,4,5]. The original array is NOT affected with resulting in array being [1,2,3,4,5].
Below is simple fiddle which confirms this:
//splice
var array=[1,2,3,4,5];
console.log(array.splice(2));
//slice
var array2=[1,2,3,4,5]
console.log(array2.slice(2));
console.log("----after-----");
console.log(array);
console.log(array2);
Splice and Slice both are Javascript Array functions.
Splice vs Slice
The splice() method returns the removed item(s) in an array and slice() method returns the selected element(s) in an array, as a new array object.
The splice() method changes the original array and slice() method doesn’t change the original array.
The splice() method can take n number of arguments and slice() method takes 2 arguments.
Splice with Example
Argument 1: Index, Required. An integer that specifies at what position to add /remove items, Use negative values to specify the position from the end of the array.
Argument 2: Optional. The number of items to be removed. If set to 0(zero), no items will be removed. And if not passed, all item(s) from provided index will be removed.
Argument 3…n: Optional. The new item(s) to be added to the array.
var array=[1,2,3,4,5];
console.log(array.splice(2));
// shows [3, 4, 5], returned removed item(s) as a new array object.
console.log(array);
// shows [1, 2], original array altered.
var array2=[6,7,8,9,0];
console.log(array2.splice(2,1));
// shows [8]
console.log(array2.splice(2,0));
//shows [] , as no item(s) removed.
console.log(array2);
// shows [6,7,9,0]
Slice with Example
Argument 1: Required. An integer that specifies where to start the selection (The first element has an index of 0). Use negative numbers to select from the end of an array.
Argument 2: Optional. An integer that specifies where to end the selection but does not include. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array.
var array=[1,2,3,4,5]
console.log(array.slice(2));
// shows [3, 4, 5], returned selected element(s).
console.log(array.slice(-2));
// shows [4, 5], returned selected element(s).
console.log(array);
// shows [1, 2, 3, 4, 5], original array remains intact.
var array2=[6,7,8,9,0];
console.log(array2.slice(2,4));
// shows [8, 9]
console.log(array2.slice(-2,4));
// shows [9]
console.log(array2.slice(-3,-1));
// shows [8, 9]
console.log(array2);
// shows [6, 7, 8, 9, 0]
S LICE = Gives part of array & NO splitting original array
SP LICE = Gives part of array & SPlitting original array
I personally found this easier to remember, as these 2 terms always confused me as beginner to web development.
Here is a simple trick to remember the difference between slice vs splice
var a=['j','u','r','g','e','n'];
// array.slice(startIndex, endIndex)
a.slice(2,3);
// => ["r"]
//array.splice(startIndex, deleteCount)
a.splice(2,3);
// => ["r","g","e"]
Trick to remember:
Think of "spl" (first 3 letters of splice) as short for "specifiy length", that the second argument should be a length not an index
The slice() method returns a copy of a portion of an array into a new array object.
$scope.participantForms.slice(index, 1);
This does NOT change the participantForms array but returns a new array containing the single element found at the index position in the original array.
The splice() method changes the content of an array by removing existing elements and/or adding new elements.
$scope.participantForms.splice(index, 1);
This will remove one element from the participantForms array at the index position.
These are the Javascript native functions, AngularJS has nothing to do with them.
Splice - MDN reference - ECMA-262 spec
Syntax
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
Parameters
start: required. Initial index.
If start is negative it is treated as "Math.max((array.length + start), 0)" as per spec (example provided below) effectively from the end of array.
deleteCount: optional. Number of elements to be removed (all from start if not provided).
item1, item2, ...: optional. Elements to be added to the array from start index.
Returns: An array with deleted elements (empty array if none removed)
Mutate original array: Yes
Examples:
const array = [1,2,3,4,5];
// Remove first element
console.log('Elements deleted:', array.splice(0, 1), 'mutated array:', array);
// Elements deleted: [ 1 ] mutated array: [ 2, 3, 4, 5 ]
// array = [ 2, 3, 4, 5]
// Remove last element (start -> array.length+start = 3)
console.log('Elements deleted:', array.splice(-1, 1), 'mutated array:', array);
// Elements deleted: [ 5 ] mutated array: [ 2, 3, 4 ]
More examples in MDN Splice examples
Slice - MDN reference - ECMA-262 spec
Syntax
array.slice([begin[, end]])
Parameters
begin: optional. Initial index (default 0).
If begin is negative it is treated as "Math.max((array.length + begin), 0)" as per spec (example provided below) effectively from the end of array.
end: optional. Last index for extraction but not including (default array.length). If end is negative it is treated as "Math.max((array.length + begin),0)" as per spec (example provided below) effectively from the end of array.
Returns: An array containing the extracted elements.
Mutate original: No
Examples:
const array = [1,2,3,4,5];
// Extract first element
console.log('Elements extracted:', array.slice(0, 1), 'array:', array);
// Elements extracted: [ 1 ] array: [ 1, 2, 3, 4, 5 ]
// Extract last element (start -> array.length+start = 4)
console.log('Elements extracted:', array.slice(-1), 'array:', array);
// Elements extracted: [ 5 ] array: [ 1, 2, 3, 4, 5 ]
More examples in MDN Slice examples
Performance comparison
Don't take this as absolute truth as depending on each scenario one might be performant than the other.
Performance test
The splice() method returns the removed items in an array.
The slice() method returns the selected element(s) in an array, as a new array object.
The splice() method changes the original array and slice() method doesn’t change the original array.
Splice() method can take n number of arguments:
Argument 1: Index, Required.
Argument 2: Optional. The number of items to be removed. If set to 0(zero), no items will be removed. And if not passed, all item(s) from provided index will be removed.
Argument 3..n: Optional. The new item(s) to be added to the array.
slice() method can take 2 arguments:
Argument 1: Required. An integer that specifies where to start the selection (The first element has an index of 0). Use negative numbers to select from the end of an array.
Argument 2: Optional. An integer that specifies where to end the selection. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array.
Splice and Slice are built-in Javascript commands -- not specifically AngularJS commands. Slice returns array elements from the "start" up until just before the "end" specifiers. Splice mutates the actual array, and starts at the "start" and keeps the number of elements specified. Google has plenty of info on this, just search.
Most answers are too wordy.
splice and slice return rest of elements in the array.
splice mutates the array being operated with elements removed while slice not.
Both return same answer but:
SPlice will mutate your original array.
Slice won't mutate your original array.
The slice( ) method copies a given part of an array and returns that copied part as a new array. It doesn’t change the original array.
The splice( ) method changes an array, by adding or removing elements from it.
Here is the slice syntax:
array.slice(from, until);
// example
let array = [1, 2, 3, 4, 5, 6]
let newArray = array.slice(1, 3)
console.log({array, newArray})
// output: array: [1, 2, 3, 4, 5, 6], newArray: [2, 3]
Note: the Slice( ) method can also be used for strings.
And here is the splice syntax:
//For removing elements, we need to give the index parameter,
// and the number of elements to be removed
array.splice(index, number of elements to be removed);
//example
let array = [1, 2, 3, 4, 5, 6]
let newArray = array.splice(1, 3)
console.log({array, newArray})
// output: array: [1, 5, 6], newArray: [2, 3, 4]
Note: If we don’t define the second parameter, every element starting from the given index will be removed from the array
// For adding elements, we need to give them as the 3rd, 4th, ... parameter
array.splice(index, number of elements to be removed, element, element);
//example
let array = [1, 2, 3, 4, 5, 6]
let newArray = array.splice(1, 3, 'a', 'b')
console.log({array, newArray})
// output: array: [1, ,'a', 'b', 5, 6], newArray: [2, 3, 4]
Related links:
Let’s clear up the confusion around the slice( ), splice( ), & split( ) methods in JavaScript
Array.prototype.slice()
Array.prototype.splice()
splice & delete Array item by index
index = 2
//splice & will modify the origin array
const arr1 = [1,2,3,4,5];
//slice & won't modify the origin array
const arr2 = [1,2,3,4,5]
console.log("----before-----");
console.log(arr1.splice(2, 1));
console.log(arr2.slice(2, 1));
console.log("----after-----");
console.log(arr1);
console.log(arr2);
let log = console.log;
//splice & will modify the origin array
const arr1 = [1,2,3,4,5];
//slice & won't modify the origin array
const arr2 = [1,2,3,4,5]
log("----before-----");
log(arr1.splice(2, 1));
log(arr2.slice(2, 1));
log("----after-----");
log(arr1);
log(arr2);
slice does not change original array it return new array but splice changes the original array.
example: var arr = [1,2,3,4,5,6,7,8];
arr.slice(1,3); // output [2,3] and original array remain same.
arr.splice(1,3); // output [2,3,4] and original array changed to [1,5,6,7,8].
splice method second argument is different from slice method. second argument in splice represent count of elements to remove and in slice it represent end index.
arr.splice(-3,-1); // output [] second argument value should be greater then
0.
arr.splice(-3,-1); // output [6,7] index in minus represent start from last.
-1 represent last element so it start from -3 to -1.
Above are major difference between splice and slice method.
Another example:
[2,4,8].splice(1, 2) -> returns [4, 8], original array is [2]
[2,4,8].slice(1, 2) -> returns 4, original array is [2,4,8]
//splice
var array=[1,2,3,4,5];
console.log(array.splice(2));
//slice
var array2=[1,2,3,4,5]
console.log(array2.slice(2));
console.log("----after-----");
console.log(array);
console.log(array2);
slice and splice are intimately connected, but yet serves very different purposes:
The slice function is used to select a portion of an array. Its purpose is its return value. Its execution does not affect its subject.
The splice function is used to remove elements from an array. Its purpose is to modify its subject. It still returns a copy of the removed items, for reference, if needed.
JavaScript Array splice() Method By Example
Example1 by tutsmake -Remove 2 elements from index 1
var arr = [ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" ];
arr.splice(1,2);
console.log( arr );
Example-2 By tutsmake – Add new element from index 0 JavaScript
var arr = [ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" ];
arr.splice(0,0,"zero");
console.log( arr );
Example-3 by tutsmake – Add and Remove Elements in Array JavaScript
var months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb'); // add at index 1
console.log(months);
months.splice(4, 1, 'May'); // replaces 1 element at index 4
console.log(months);
https://www.tutsmake.com/javascript-array-splice-method-by-example/
The difference between Slice() and Splice() javascript build-in functions is,
Slice returns removed item but did not change the original array ;
like,
// (original Array)
let array=[1,2,3,4,5]
let index= array.indexOf(4)
// index=3
let result=array.slice(index)
// result=4
// after slicing=> array =[1,2,3,4,5] (same as original array)
but in splice() case it affects original array; like,
// (original Array)
let array=[1,2,3,4,5]
let index= array.indexOf(4)
// index=3
let result=array.splice(index)
// result=[4,5]
// after splicing array =[1,2,3] (splicing affects original array)
There are 3 differences:
Splice will remove the selected elements from the original array and return them as a new array -Notice that the original will no longer have them-. Slice will create a new array with the selected elements without affecting the original one.
Splice receives as parameters the start index and how many elements to remove from that point. Slice receives 2 indexes, start and end.
Splice can be used to add elements at a specific position in the array by passing optional parameters.
These two methods are very confusing for beginners. I have researched and found 4 key points in slice and splice. You can read more in detail about slice vs splice.
Slice in JavaScript
Slice just returns a specified number of elements from an array. For example you have an array of 10 elements and you want to just get 3 elements from 2nd index.
It doesn't modify the original array but returns the number of elements.
The syntax of the slice is array.slice(startingIndex, elementCount)
Splice in JavaScript
Splice can also return the selected elements from the array same as the slice but it modifies the original array.
You can add a new element in an array using splice on a specific index
You can remove specified elements as well as add new elements at the same time.
The syntax of using splice is array.splice(startingIndex, removeCounter, newElement(s)[optional])
Summary
The purpose of the slice is to get only selected elements from array and it doesn't modify the original array.
The splice should be used when you want to modify the original array by removing elements and adding new elements.

Slicing an Argument on Filter Array?

I have been doing this course for hours on free code camp, however, I found a solution that I do not understand and I am trying to put comments on each line to record as I achieve and understand it for future references and I already understand some lines but I cannot understand some parts of this code:
function destroyer(arr) {
// let's make the arguments part of the array
var args = Array.prototype.slice.call(arguments); // this would result into [[1, 2, 3, 1, 2, 3], 2, 3]
args.splice(0,1); // now we remove the first argument index on the array so we have 2,3 in this example
// I DO NOT UNDERSTAND THESE CODES BELOW
return arr.filter(function(element) {
return args.indexOf(element) === -1;
});
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
I already check on documentation and I find it hard to understand seems the code in this sample are very different. I would really appreciate your help!
arr in the section of code you don't understand refers to the first argument passed to the destroyer function; in this case, the array [1, 2, 3, 1, 2, 3]
arr.filter is using the Array.filter method to create a "filtered" version of the array with only those values that pass the "test" defined by function(element) { return args.indexOf(element) === -1; }
That function uses Array.indexOf to check if the sliced args array (which you correctly identified as being equal to [2, 3]) contains the given element. Because indexOf returns -1 when the element is not found, checking for that value is equivalent to checking that the specified element is NOT in the array
The result of all of this - and the return value of the function destroy - will be the array [1, 1], representing a filtered version of the array passed to destroy that contains all the values not equal to the other values passed to destroy.
Array.slice is part of the arrays prototype;
prototype methods are only accessable on instances of Classes.
var arr = ['a', 'b', 'c', 'd'];
// [] is JavaScript shorthand for instantiating an Array object.
// this means that you can call:
arr.slice(someArg1);
arry.splice(someArg2);

Categories

Resources