Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 27, 2022 11:25 pm GMT

Select unique elements from an Array using: lastIndexOf() & indexOf()

Hello guys! So, today I am going to show you how to use the following built-in array methods (lastIndexOf() & indexOf()) to select unique elements from an array.

indexOf()

The indexOf() method of the array returns the first index or position at which a given element can be found in the array. It returns -1 if the element is not found.
Eg:

const numberArray = [1,2,3,4];const index = numberArray.indexOf(3);console.log(index) => 2const noIndex = numberArray.indexOf(9);console.log(noIndex) => -1

lastIndexOf()

The lastIndexOf() method of the array returns the last index or position at which an element can be found in an array. The array is searched backwards.
Eg:

const numberArray = [1,2,3,4,5,7,3,6,9];const lastIndex = numberArray.lastIndexOf(3);console.log(lastIndex ) => 6const noLastIndex = numberArray.lastIndexOf(90);console.log(noLastIndex ) => -1

Now, let's go into the business of the day.
NOTE: The purpose of this tutorial is not to make an array of repeated values a unique array, rather it is to pick elements that appear only once in a repeated array.

Example

Given an array of repeated values:

const repeatedVals = [5, 7, 3, 9, 4, 9, 8, 3, 2, 7, 2];
We are going to output a new array of unique values.

function uniqueValues(arr) {  const uniqueVals = [];  return uniqueVals}

Explanation: we created a function, inside the function, we created an empty array to hold the unique values and then return that new array. Next, we are going to write our for-loop and some conditions.

// [5, 7, 3, 9, 4, 9, 8, 3, 2, 7, 2];function uniqueValues(arr) {  const uniqueVals = [];  const lenOfArr = arr.length;  for (let i = 0; i < lenOfArr; i++){    const val = arr[i];    if (arr.lastIndexOf(val) === arr.indexOf(val)) {      uniqueVals.push(val)    }  }  return uniqueVals}uniqueValues(repeatedVals)

Output-

[5, 4, 8]

Explanation:
The if conditional simply checks if the returned indices of both methods are equal. In the case where they are not equal, it simply means that the current value has a duplicate in the array.

Thank you for checking out this post. In case of any errors or suggestions, kindly notify me.


Original Link: https://dev.to/felistus/select-unique-elements-from-a-array-using-lastindexof-indexof-5dnh

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To