How to use Array Slice() Method In Javascript
This method returns the selected elements in a new array object. This method gets the elements starting from the specified start argument and ends at excluding the given end argument.
Syntax:
array.slice(start, end)
Parameters:
- start: This parameter is optional. It specifies the integer from where to start the selection (index starts from 0). Negative numbers are used to select from the end of the array. If not used, it acts like “0”.
- end: This parameter is optional. It specifies the integer from where the end of the selection. If not used all elements from the start to the end of the array will be selected. Negative numbers are used to select from the end of the array.
Example: This example first sorts the array and then selects them one by one if they are non-unique.
let arr = [89, 89, 11, 2, 3, 4, 2, 4, 5, 7];
let sort_arr = arr.slice().sort();
let res = [];
function gfg_Run() {
for (let i = 0; i < sort_arr.length - 1; i++) {
if (sort_arr[i + 1] == sort_arr[i]) {
res.push(sort_arr[i]);
}
}
console.log("Non Unique values are: " + res);
}
gfg_Run();
Output
Non Unique values are: 2,4,89
JavaScript Get all non-unique values from an array
We have given a JavaScript array, and the task is to find all non-unique elements of the array. To get all non-unique values from the array here are a few examples.
These are the following methods to get all non-unique values from an array:
Table of Content
- Using Array Slice() Method
- Using for loop
- Using filter() Method
- Using indexOf() Method
- Using reduce() and an object to count occurrences: