Eliminate any duplicated numbers present within an array of numerical values

Recently, I came across a puzzling question for practice that left me intrigued by the two possible outcomes it could be seeking.

Naturally, I am eager to explore both solutions.

Consider an array given as:

let arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];

I interpret the question as requiring the final result to be either of these two possibilities:

let finalResult = [1, 2, 3, 4, 5, 8, 9, 10];

OR:

let finalResult = [1, 9, 10];

The distinction lies in one solution removing all duplicate numbers while retaining the unique ones, and the other focusing on isolating the non-duplicate numbers.

Which leads me to the desire to craft two functions, each catering to one of the above scenarios.

An individual shared the following code snippet resulting in my second solution:

let elems = {},

arr2 = arr.filter(function (e) {
   if (elems[e] === undefined) {
       elems[e] = true;
    return true;
  }
  return false;
});
console.log(arr2);

As for the function necessary for the first scenario (removing all duplicates), I find myself uncertain.

Answer №1

Utilizing the power of Set combined with Array.from()

let arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];

console.log(Array.from(new Set(arr)));

An alternative method using regex

Explanation of regex usage can be found here

let arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];

let res = arr
  .join(',')
  .replace(/(\b,\w+\b)(?=.*\1)/ig, '')
  .split(',')
  .map(Number);

console.log(res);

An alternative approach using objects

let arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];

let obj = arr.reduce((acc, val) => Object.assign(acc, {
  [val]: val
}), {});

console.log(Object.values(obj));

Answer №2

For a straightforward solution, try using the array.filter method like this:

let numbers = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];
let uniqueNumbers = numbers.filter((element, index, array) => array.indexOf(element) === index).sort((a, b) => a - b);
console.log(uniqueNumbers);

If you need another filter for different results, consider implementing it with an additional filter statement:

let numbers = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];
let nonRepeatingNumbers = numbers.filter((element, index, array) => array.filter(num => num === element).length === 1).sort((a, b) => a - b);
console.log(nonRepeatingNumbers);

Answer №3

To eliminate duplicates in the first part, utilize Set() and Spread Syntax.

let arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];
let res = [...new Set(arr)]
console.log(res)

For the second part, employ reduce()

let arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];
//to get the object with count of each number in array.
let obj = arr.reduce((ac,a) => {
  //check if number does not occur before then set its count to 1
  if(!ac[a]) ac[a] = 1;
  //if number is already in object increase its count
  else ac[a]++;
  return ac;
},{})
//Using reduce on all the keys of object means all numbers.
let res = Object.keys(obj).reduce((ac,a) => {
  //check if count of current number 'a' is `1` in the above object then add it into array
  if(obj[a] === 1) ac.push(+a)
  return ac;
},[])
console.log(res)

Answer №4

To achieve this, utilize the power of closure in combination with Map.

let numbers = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];

const buildUniqueArray = arr => {
  const mapObj = arr.reduce((acc, element) => {
    acc.has(element) ? acc.set(element, true) : acc.set(element, false)
    return acc
  }, new Map())
  
  return function(hasDuplicates = true) {
    if(hasDuplicates) return [...mapObj.keys()]
    else return [...mapObj].filter(([key, value]) => !value).map(([k, v])=> k)
  }
}

const uniqueNumbers = buildUniqueArray(numbers)

console.log(uniqueNumbers())
console.log(uniqueNumbers(false))

Answer №5

You have the ability to generate two arrays simultaneously

let arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];
let unique = new Set();
let repeated = Array.from(arr.reduce((acc, curr) => {
acc.has(curr) ? unique.delete(curr) : acc.add(curr) && unique.add(curr);
return acc;
}, new Set()));

console.log(Array.from(unique))
console.log(repeated)

Answer №6

To create a hash object in JavaScript, you can utilize the Array.prototype.reduce() method. This will assign numbers in an array as keys and their corresponding repeated occurrences as values in the hash object.

Afterwards, you can make use of the Object.keys() method:

  • Eliminate duplicates by accessing Object.keys(hash)
  • Filter out duplicates to obtain numbers with only one occurrence using Array.prototype.filter()

Here is the code snippet for illustration:

const arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];
const hash = arr.reduce((a, c) => (a[c] = (a[c] || 0) + 1, a), {});

// Resulting in: [1, 2, 3, 4, 5, 8, 9, 10]
const finalResultOne = Object.keys(hash);

// Output: [1, 9, 10]
const finalResultTwo = Object.keys(hash).filter(k => hash[k] === 1);

console.log('Final Result One:', ...finalResultOne);
console.log('Final Result Two:', ...finalResultTwo);

Answer №7

To prevent duplicates in an array, you have the option to either sort the array first and then filter it by checking for duplicates on one side or both sides.

var array = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10],
    result1,
    result2;

array.sort((a, b) => a - b);

result1 = array.filter((v, i, a) => a[i - 1] !== v);
result2 = array.filter((v, i, a) => a[i - 1] !== v && a[i + 1] !== v);

console.log(...result1);
console.log(...result2)

Answer №8

Just like many others have pointed out, the solution for the first question is simply using [...new Set(arr)]

To solve the second question, you can filter out elements that occur more than once in the array:

const arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];

const count = (arr, e) => arr.filter(n => n == e).length

const unique = arr => arr.filter(e => count(arr, e) < 2)

console.log(unique(arr));

Answer №9

Here is a code snippet that removes duplicates from an array and prints the unique elements:
var arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];
var map = {};
var finalResult = [];
for (var i = 0; i < arr.length; i++) {
  if (!map.hasOwnProperty(arr[i])) {
    map[arr[i]] = true;
    finalResult.push(arr[i]);
  }
}

//if you need it sorted otherwise it will be in order
finalResult.sort(function(a, b) {
  return a - b
});

console.log(finalResult);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason why Discord.js is not utilizing the message object?

My goal was to send a series of buttons ahead of time for collection, but I encountered an issue when running the collector. The error message displayed: const collector = message.createMessageComponentCollector({ componentType: ComponentType.Button, ...

jQuery prettyPhoto: Issue with Click Event not functioning

I have been utilizing the jQuery prettyPhoto plugin to display inline HTML content. The content includes a link that is meant to close the prettyPhoto popup and trigger a custom script. Although the popup functions properly, for some reason, the click even ...

Accessing an object within an array in MongoDB: Step-by-step guide

Expressing my thoughts accurately in words is a challenge for me, so I'll provide an example instead: [ { 'description': 'animals', 'examples': [ { 'name': 'Lion', &apo ...

Is it possible to modify this jquery keyboard navigation to accommodate different tags and additional keyboard functions?

I am currently in the process of developing a basic website featuring images arranged vertically on the page. My goal is to enable smooth scrolling between these images using the keyboard arrow keys. With the assistance of this forum, I have been provided ...

Issue: A request is not pending for flushing during the testing of an AngularJs service

As a beginner in AngularJs, I am currently working on my first unit test. In order to test the service I created, I wrote a test that simply returns a single Json object. However, whenever I run the test, I encounter the error mentioned in the title. I am ...

What is the best way to transform an array into valid JSON format?

Looking to reformat my array in JSON form product[0]['product_id'] product[0]['name'] .... product[1]['product_id'] product[1]['name'] ... After using JSON.stringify(), the output is as follows: {"0":{"product_id" ...

create a word with only **one** bold letter in the word ionic-angularjs

Can someone please guide me on how to style only a specific letter within a word using angularJS? Specifically, I want to make the first letter bold while keeping the rest of the word in normal font. For instance, if I have an array of words like: var Wor ...

Do you think React hooks will totally take over the role of creating class-based components?

Are React hooks poised to entirely replace class-based component creation? Will companies quickly integrate React hooks in the future? Is it worth learning React hooks? ...

Utilizing Ionic for local data retention

Seeking assistance with connecting my app to local storage in order to save data on the user's device without resetting every time the app is closed. Struggling to link local storage to an array of objects. Any guidance would be highly appreciated. Re ...

The result obtained from response.download() is saved as a blob that may contain undefined elements

I am in the process of developing a client-server certificate generator. In terms of the Backend, I have set up two endpoints: / This endpoint receives a JSON containing extracted data from inputs, sanitizes them, and determines if they are valid or not ...

"Surprising outcomes when using the splice method on an array

Exploring the functionalities of Array.splice(). deleteCount: A whole number indicating the quantity of old array elements to eliminate. Understood. It seems clear. I aim to extract the final 4 items in the array. I trust that refers to elements? arr. ...

Load the ReactJS component seamlessly by running an AJAX call in the background to prevent the page from freezing

Does the page freeze for a few seconds when making an ajax call in componentDidMount? I find that I am unable to click or select anything until the ajax call is done, even though it's just fetching 3MB of data. The entire page appears to finish render ...

Steps to remove the initial text entry before creating a GeoJSON document

Utilizing nodeJs and postgres to visualize linestrings on a website. The query returns a geojson feature collection. Using json_build_object on the serverside to generate GeoJSON Feature collection. const a = parseInt(request.params.start) cons ...

obtaining selections from a dropdown menu and transferring them to an unordered list using jquery

Currently, I am in the process of developing a plugin that transforms select boxes into visually appealing elements. This transformation involves converting select boxes on a page into definition lists, where each definition description contains a nested u ...

Why is the response undefined when I resize an image twice using a JavaScript promise chain?

When I attempt to resize an image using the sharp library twice in my route handler, the result returned is undefined. Despite the resized images being displayed, it seems that calling image.resize and .toBuffer() multiple times is causing corruption in th ...

Tips for managing NaN values within mathjs.evaluate

console.log(mathjs.evaluate("(goodCount/(goodCount+reject_count))>0.99", { goodCount: 0, reject_count: 0, Total_Planned_time: 10 })) I am facing an issue where if both goodCount and reject_count are zero, this function returns NaN. Howe ...

The function parameter in Angular's ngModelChange behaves differently than $event

How can I pass a different parameter to the $event in the function? <div class='col-sm'> <label class="col-3 col-form-label">Origen</label> <div class="col-4"> <select ...

MongoDB suggests

I'm currently developing an app that requires autocomplete functionality for search. I've started implementing it using regular expressions (regexp), but I'm unsure if this is the optimal approach. Each new character input in the search bar ...

transfer data from local array to global variable

Need help with returning array values using console.log(array);, currently it's displaying empty value []. Any tips or suggestions would be greatly appreciated. var array = []; var maxLength = 3; var delay = 250; //Shortened the delay var ticker = {}; ...

My onClick AngularJS function contains a for loop that is not functioning properly upon initial click

When I click on a student's name in my AngularJS app, the program is supposed to show the student's full name and list of tuitions. However, I am encountering an issue where the for loop does not work on the first click, but it works fine on the ...