concatenate problems with concat function - javascript

In this case of concat() function, i don't get why the value of the length property is not concatenated to array. Also when i change the value of length property to some random value, the first two properties are ignored as well when i concatenate them.
1st case:
let arr = [1, 2];
let arrayLike = {
0: "something",
1: "else",
[Symbol.isConcatSpreadable]: true,
length: 2
};
alert( arr.concat(arrayLike) ); // 1,2,something,else
2nd case:
let arr = [1, 2];
let arrayLike = {
0: "something",
1: "else",
[Symbol.isConcatSpreadable]: true,
length: "random",
};
console.log( arr.concat(arrayLike) ); // 1,2

Your arrayLike object is sort of mimicking being an array like arr. So if you're treating it like a normal array, then why would you expect the value of length to be counted as a value in the array?
In your actual array, arr, you would have arr.length == 2. But 2 is not a value in the array, it just tells you how many values are in the array (two values, 1 and 2). This is how JavaScript knows how many values to look for. If you were to set arr.length = 1, suddenly JavaScript would only show one value instead of two. See here:
let arr = [1, 2];
console.log(arr); //[1, 2]
arr.length = 1;
console.log(arr) //[1]
Similarly, your length: 2 property in your arrayLike object is being used to represent an array with 2 elements. If you set it to something that isn't a number, JavaScript no longer knows how many values could be in the "array", so it apparently simply counts it as 0 - an empty array.

Related

Javascript Arrays inside object

i have a arrays inside object like this for example:
{1: Array(4), 2: Array(4), 3: Array(4)}
1: (4) ["11111", "2020-04-02", "14:07", 1]
2: (4) ["22222", "2020-04-02", "14:07", 2]
3: (4) ["3333333", "2020-04-02", "14:07", 3]
(from console log)
in my code there is a option to add array and delete array .
And if I delete the second array for example its will become to this:
{1: Array(4), 3: Array(4)}
1: (4) ["11111", "2020-04-02", "14:07", 1]
3: (4) ["3333333", "2020-04-02", "14:07", 3]
(from console log)
How do I make the third object become to 2 ?
Make the object manage from the low to the high
THANKS.
If you convert your object to an array-like then you can use array methods with it.
An array-like object basically needs a length property and keys that are positive integers. The length needs to be set to one more than the highest index. So, if you have keys 1, 2, 3 then you need length: 4. Yes, it's a bit misleading since there are only three elements but length is more accurately called "next available index".
At any rate, if you transform your object, then you can use Array#splice and set the target using Function#call. Most array methods are intentionally generic so they can work on anything that's an array-like:
const obj = {
1: ["foo"],
2: ["bar"],
3: ["baz"],
length: 4
}
//delete starting from index 2 and remove 1 item
Array.prototype.splice.call(obj, 2, 1)
console.log(obj);
Note how the indexes after the deleted one shifted and the length was also adjusted automatically.
If you don't know what the length is currently, you can easily find it:
const obj = {
1: ["foo"],
2: ["bar"],
3: ["baz"]
}
const keys = Object
.keys(obj) //get all keys
.map(Number) //convert to numbers
.filter(key => Number.isInteger(key) && key >= 0); //leave only positive integers
//find the highest
const highestKey = keys.reduce((a, b) => Math.max(a, b), -1);
//set the length to the next possible index
obj.length = highestKey + 1;
//delete starting from index 2 and remove 1 item
Array.prototype.splice.call(obj, 2, 1)
console.log(obj);
In the object above, when you delete the second array, only that key is removed and this has no impact on other keys. Because object keys act as an identifier to access the location of value corresponding to that key.
If you want that other keys should reset accoding to order. Please use array of arrays instead of objects having arrays as values.
Array - ordered items with numeral indices
Object - unordered items with any valid string or number indices.
If it is required to use object, here's the solution to manually do it -
For the index i that needs to be removed, parse the next indices (numerically greater than i) to take key = key - 1, i.e., decreasing their index key by 1.
// index is treated from 1 to n.
const deleteElement = (delete_index, obj) => {
const keyCount = Object.keys(obj).length;
// move all elements with keys > delete_index to previous index
for(let i=delete_index; i<=keyCount; i++) {
obj[i] = obj[i+1]
}
// delete last element
delete obj[keyCount]
}
use splice methodarr.splice(2,1) where first argument is index and second will be number of items to remove from array.

What kind of object is this in javascript?

I have an object 'obj'. Let's say we don't know where it came from, for a moment.
If I do
console.log(JSON.stringify(obj));
I obtain
[{"foo":101,"bar":1,"foobar":0},{"foo":102,"bar":1,"foobar":0}]
What kind of object is this?
I'm asking for I see two behaviours I can't understand:
1) It seems to be an array of objects (?) so I would expect
console.log(obj[0])
to return:
{"foo":101,"bar":1,"foobar":0},{"foo":102,"bar":1,"foobar":0}
instead it returns:
{"foo":101,"bar":1,"foobar":0}
2) I would expect
for (var somevar in obj){
console.log(JSON.stringify(somevar));
}
to return
first step: {"foo":101,"bar":1,"foobar":0}
second step: {"foo":102,"bar":1,"foobar":0}
instead it returns
first step: "0"
second step: "1"
Can someone explain me the nature of this object and why these two cases (expecially the second) return such results?
The obj is array or objects. It has two objects at index 0 and 1 that is why when you do console.log(obj[0]); it gives you only {"foo":101,"bar":1,"foobar":0}. Which is the object at index 0.
For second question, the for (var somevar in obj) loops over each key of obj and since it is a array data type the keys of the array is always its index value. That is why you get 0 and 1 in console. To make that work you need to do var somevar of obj in the for that will then consider the value and not the key of obj array.
var obj = [{"foo":101,"bar":1,"foobar":0},{"foo":102,"bar":1,"foobar":0}];
for (var somevar of obj){
console.log(JSON.stringify(somevar));
}
For your particular first problem - When we access an array by its index it returns value of that particular index. e.g
var first_array = ['A', 'B', 'C', 'D'];
var secound_array = [{"foo":101,"bar":1,"foobar":0},{"foo":102,"bar":1,"foobar":0}];
Syntex to access array data with index is array_variable[index], where index is numeric value. for e.g.
first_array[0] // output = A
first_array[2] //output = C
secound_array[0] // output = {"foo":101,"bar":1,"foobar":0}
This is your first problem solution because you are accessing an element by array index. Index of an array starts from 0.
For your second problem, the for..in statement iterates with the index, not the value. If I write like below code -
for (var somevar in secound_array){
console.log(JSON.stringify(somevar));
}
the output is
first step: 0
second step: 1
If you want output like
first step: {"foo":101,"bar":1,"foobar":0}
second step: {"foo":102,"bar":1,"foobar":0}
You need to write like below code -
for (var somevar of secound_array){
console.log(JSON.stringify(secound_array[somevar])); // here somevar is index of the item
}
For more info click here
You can also check for...of. e.g.
for (let o of secound_array) {
console.log(o)
}
To the first question:
You have two elements in your array:
var obj =
[
{"foo": 101, "bar":1, "foobar": 0}, //first element at index 0
{"foo": 102, "bar":1, "foobar": 0} //second element at index 1
];
console.log(obj[0]);
If you write console.log(obj[0]); then you get first element and not 2 elements at once because at index 0 you have only one element. And this is correct.
To the second question:
var obj = [{"foo": 101, "bar":1, "foobar": 0},{"foo": 102, "bar":1, "foobar": 0}];
for (var somevar in obj){
console.log(JSON.stringify(somevar));
}
This put in the console:
At first step: "0"
At second step: "1"
And this is correct too. For your wish you have to use for of loop and not for in because for in gives you the index of an element and not an element like for of.
Check the difference between for in and for of:
var arr = [ 3, 5, 7 ];
for(var i in arr) {
console.log(i); // 0, 1, 2
}
console.log('-----');
for(var i of arr) {
console.log(i); // 3, 5, 7
}
Arrays are objects in JavaScript. So that behavior is totally expected. The indices are keys to an array.
So when you do
console.log(obj[0])
You simply access the first item in the array
Then in the second case you are simply logging out the stringified keys '0' and '1'

Find common elements within dynamic array's object elements Javascript

There were a lot of questions asked about this topic, but I couldn't find the answer that addressed directly the issue I am having.
Here is one: Find common elements in 1 array using Javascript
The first difference is that I have a different type of array, its elements are objects with key-value pair, where key is the string and the value is an array of integers.
The second difference is that array is dynamic meaning that sometimes it may have zero elements and the other times it may have 3 object elements.
I am sharing the sample array below:
const array = [
{"key1":[1,2,3]},
{"key2":[2,3,4]},
{"key3":[2,5,6]},
];
The third difference is that the order of elements matters so that final result should output the values of the first element that exist in all subsequent arrays.
The result should be:
const result = [2];
Since 2 is the only common integer of these three elements.
As mentioned array sometimes might have just 1 or 2 or no elements in it and those cases should be accounted.
Edit 1: as asked in the comments the values of array are unique
Since a value can appear in array only once, you can concat the arrays, count the number of appearances, and filter our those that are not equal to the length of the original array.
const findRecuring = (array) =>
[...
[].concat(...array.map((o) => Object.values(o)[0])) // combine to one array
.reduce((m, v) => m.set(v, (m.get(v) || 0) + 1), new Map()) // count the appearance of all values in a map
] // convert the map to array of key/value pairs
.filter(([, v]) => v === array.length) // filter those that don't appear enough times
.map(([k]) => k); // extract just the keys
/** Test cases **/
console.log('Several:', findRecuring([
{"key1":[6,1,2,3,8]},
{"key2":[2,6,3,4,8]},
{"key3":[2,5,6,8]},
]).join());
console.log('None: ', findRecuring([
{"key1":[9,0,11]},
{"key2":[2,6,3,4,8]},
{"key3":[2,5,6,8]},
]).join());
const array = [
{"key1":[1,2,3]},
{"key2":[2,3,4]},
{"key3":[2,5,6]},
];
You could iterate over and store how often a value appears in the array for each value:
var common=new Map();
array.forEach(function(obj){
//var values=new Set(Object.values(obj)[0]);//make unique values out of array
var values=Object.values(obj)[0];//no need for uniqueness as OP states that they are already unique..
values.forEach(function(val){
common.set(val,(common.get(val)||0)+1);
});
});
Now youve got a map with all elements and their appearance in the main array. So now you can simply compare:
var result=[];
common.forEach(function(appearance,el){
if(appearance===array.length){
result.push(el);
}
});
http://jsbin.com/xuyogahija/edit?console
You could get first the arrays in an array without using different keys and then lookup each element if it is in the other array.
let array = [{ key1: [1, 2, 3] }, { key2: [2, 3, 4] }, { key3: [2, 5, 6] }],
result = array
.map(o => o[Object.keys(o)[0]] || [])
.reduce((a, b) => a.filter(c => b.includes(c)));
console.log(result);

Inserting an object so the array stays sorted

I have an enum of different Steps
export enum StepCategory {
START = 0,
POSITION_1 = 1,
TRANSPORT = 2,
RECEIVER = 3,
END = 4,
NO_STEP_MATCH = 5
}
This will later result in an array, where for every Step I have an object. The Problem is I won't load all the information at once, so i can'tdo a simple for-loop and push each item chronogically. I could be that I first load the value for Step 4, so my array would be:
var array = [{"END" , "POSITIVE"}]
Afterwards I would get the Info for Step 2, then I would have:
var array = [{"END", "POSITIVE"}, {"TRANSPORT", "POSITIVE"}]
But this is not sorted.
What should I do? Should I declare an array of 6 undefined values
var array = [undefined, undefined, undefined, undefined, undefined, undefined]
This way I wouldn't need any sorting-algorithm after each Update, and can just push the value at the right position.
Just some small Info: I use AngularJS 1, Typescript and Lodash
In plain Javascript, you could sort it with an object and the assigned values of the key.
var StepCategory = { START: 0, POSITION_1: 1, TRANSPORT: 2, RECEIVER: 3, END: 4, NO_STEP_MATCH: 5 },
array = [["END", "POSITIVE"], ["TRANSPORT", "POSITIVE"]];
array.sort(function (a, b) {
return StepCategory[a[0]] - StepCategory[b[0]];
});
console.log(array)
First of all, this is - as someone mentioned in the comments - not syntactically correct:
var array = [{"END", "POSITIVE"}, {"TRANSPORT", "POSITIVE"}]
I assume that this was just a typo writing this question. Additionally if you actually use the enum in your array as key and just left it out for demonstration purposes, I would expect your array of objects to look something like this:
var array = [{StepCategory.END: "POSITIVE"}, {StepCategory.TRANSPORT: "POSITIVE"}]
In order to sort this with LoDash you could use something like this:
var sortedArray = _.sortBy(array, i => Object.keys(i)[0]);
This sorts your array by the value of the first key of each object which refers to your enum value.

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.

Categories

Resources