I am looking for a unique array that is distinct and can be used in a reusable function

I'm struggling to create a unique array using this function.

---Here is the Function I'm Working With---

var Array = [2, 0, 1, 9, 1, 3, 2, 4, 5, 5, 3, 4]

function uniqueArrayValues(val){
    var newArray=[];
    for(var i=0 ; i < val.length; i++){
        if (newArray.indexOf(val[i]) === -1){
            newArray.push(val[i])
        }
    }
    return newArray
}

Answer №1

It looks like you intended to write

if (newArray.indexOf(val[i]) == -1) // checking if it does NOT exist yet

rather than

if (newArray.indexOf(val[i]) > -1)

Answer №2

If you want to filter out duplicate elements from an array, you can simply use the Array.filter() method like this:

var arr = [2, 0, 1, 9, 1, 3, 2, 4, 5, 5, 3, 4];
var uniqueArray = arr.filter((elem, index, self) => self.indexOf(elem) === index);
console.log(uniqueArray);

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

Looking for guidance on where to find a functional code sample or comprehensive tutorial on working with ViewMetadata in Angular2

I am currently trying to understand the relationship between viewmetadata and the fundamental use of encapsulation: ViewEncapsulation, including ViewEncapsulation.Emulated and ViewEncapsulation.None. Here is a link for further information: https://angula ...

Retrieving the text or value of an ASP.NET label using JavaScript

One of my challenges is transferring a string of data from C# to JavaScript in ASP web forms. My plan involves setting the data as a text for an ASP label in C#, then extracting the label's text by ID in JS. This is the C# code (ascx.cs file): L ...

Analyzing past values within an array for the Insertion Sort procedure

Currently, I am implementing the insertion sort algorithm. This algorithm involves comparing array elements with previous elements in the array. To accomplish this, I have created nested loops: scanf("%d", &size); //accepts array size int array[size] ...

Looking to extract, interpret, and display PDF documents using React?

I'm working on displaying a PDF file from an external URL. My goal is to extract text from the PDF for analysis, and then present a specific section of a page to users in my React application. This will involve cropping the content using coordinates o ...

Modify path and refresh display upon ajax call to node server

Recently, I made the decision to utilize a Node server as a proxy for making API calls to third-party public APIs from my front end. After successfully sending a request to my Node endpoint and then to the third-party API, I received the expected response. ...

Is there a way to search through nested, nested arrays of JSON data using JSON_TABLE in SQL?

Hey there! I'm new to JSON and I'm trying to query a complex JSON data structure using JSON_TABLE. Here is the data and the query I've come up with. The problem I'm facing is that the phone number is nested within an array and I'm ...

What is the most effective way to access nested elements by index in JavaScript?

I am looking to design a user-friendly form that presents questions for users to navigate, revealing different answers/questions based on their responses. For example: var json = { "Did you restart the computer?": [ { ...

Optimize Page Speed by Delaying the Loading of Slideshow Images

My main issue with reducing my pagespeed is the slideshow I have implemented. I currently have 17 rather large images in the slideshow, but for simplicity, I will only show the code for 3 images below. I am trying to find a way to load the first image as a ...

Is it possible to trigger a script tag based on certain conditions using a JavaScript function?

I'm currently working with Angular and have a requirement to trigger a third party script from a function located within another script tag. Here's an example scenario: Within the index.html file let displayOnHomepage = () => { if (win ...

Is there a more efficient method to choose specific UV coordinates from a texture for presentation on a sprite using three.js?

I've got a texture sheet that contains various game HUD elements UV packed together in one texture. Currently, I find myself having to create a clone() of the texture for each individual part of the GUI, then create a material using this texture in o ...

What steps do I need to follow to upload an image file through Socket.IO?

For my school project, I am developing a chat application and facing a challenge with implementing an onClick event to trigger a function that utilizes socket-io-file-upload to prompt the user to select a file for upload. This functionality is detailed in ...

Error occurred while initiating Angular frontend application with npm

https://i.sstatic.net/JCy3s.png > ng serve sh: ng: command not found npm ERR! code ELIFECYCLE npm ERR! syscall spawn npm ERR! file sh npm ERR! errno ENOENT npm ERR! <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c4b2a ...

Images in Android webview disappearing after first load

When it comes to loading a local HTML file with local images into a WebView on Android, everything seems to work fine on emulators and newer devices. However, I encountered an issue with a much older device running Android 2.3.4. Initially, the images disp ...

Error encountered in vue.js due to a ReferenceError when the resize event is used

I'm having trouble obtaining the window height when resizing, and I keep encountering the error ReferenceError: calcOfSliderHeight is not defined. Can someone explain what's happening? Here is my code: let example = new Vue({ el: '#exam ...

Enable the ability to input a value of -1 by clicking on a button or link, but only allow it once (the first click) without needing to disable the button or

I am working with the following script: <script language=javascript> function process(v){ var value = parseInt(document.getElementById('v').value); value += v; document.getElementById('v').value = valu ...

Display the dropdown selected value within a Laravel Blade template

I am facing an issue with passing the selected value from a drop-down to another Blade file in Laravel. I have tried using Ajax and jQuery, but it doesn't seem to work for me. I want to display the selected value on the content.blade.php page without ...

What is the best method to update the content of one div with content from another page using AJAX?

Having trouble achieving smoother page loads? My goal is to utilize AJAX to specifically fetch a certain div from another page and then swap out the content of a div on this current page with the response. Below is my JavaScript script that uses AJAX to r ...

The issue of passing state in React Router v4 Redirect unresolved

I have a specific private route, /something, that I only want to be accessible when logged in. I've used Redirect with the state parameter set, however, when I try to access it at the destination, location.state is showing as undefined. Here is how I ...

Is this the proper formatting for JavaScript code?

Having trouble changing the CSS of elements that match b-video > p with an embed element using JQuery. Here's my code: $('div.b-video > p').has('embed').attr('style','display:block;'); Can anyone help me ...

Invoke the REST API when a checkbox is selected

I have a React component that I need help with: import * as React from 'react'; import './Pless.css'; interface Props { handleClose: () => void; showPless: boolean; } export class Pless extends React.Component<Props> ...