DEV Community

Obieze Ezeugo Felistus
Obieze Ezeugo Felistus

Posted on

 

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) => 2

const noIndex = numberArray.indexOf(9);
console.log(noIndex) => -1
Enter fullscreen mode Exit fullscreen mode

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 ) => 6

const noLastIndex = numberArray.lastIndexOf(90);
console.log(noLastIndex ) => -1
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)