How come I'm getting a numerical output instead of an array after using the array.push() method in this code?

In need of a custom function to append an element to the end of an array, I encountered a requirement: if this new element shares its value with any existing elements in the array, it should not be appended. For instance, adding 2 to [1,2] should result in [1,2] only.

This is the code snippet I came up with:

function add(arr, elem) {

    if (arr.indexOf(elem) != -1){
        return arr;
    }

    else {
        let newArr = arr.push(elem); 
        return newArr; 
    }

}

console.log(add([1,2],3)); // Expected output: [1,2,3], but received '3' instead

Can anyone shed light on why the 'newArr' array was not returned in the else block, and a number was returned instead?

Answer â„–1

When using Array.push, keep in mind that it does not return the entire array but rather the count of the new array.

Here is an example to demonstrate this:

const colors = ['red', 'blue', 'yellow'];
const count = colors.push('green');
console.log(count); // expected output: 4
console.log(colors); // expected output: Array ["red", "blue", "yellow", "green"]
  • If you are wondering about returning colors.push('green'), remember that it simply gives you the number of elements in the updated array after the push operation.

Answer â„–2

To display your current values, make sure to return the arr.

function addUniqueElement (arr, element){ 
      if (arr.indexOf(element) != -1){
           return arr;
      }
      arr.push(element); 
      return arr;
}

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

retrieve HTML content from XML document using the correct user input

I am looking to create a section of an HTML page that can only be accessed through a specific code. The page is coded using pure HTML, CSS, and JavaScript. Here is the proposed logic: User inputs a string into a form Upon clicking the submit button, an ...

Is there a way to verify if a Backbone.View is actively displayed in the DOM?

Is there a way to determine if a Backbone.View is currently rendered in the DOM, so that I do not need to rerender it? Any suggestions on how this can be achieved? Thanks and regards ...

"Unleashing the fun: incorporating a variety of random songs into your

My goal is to create a central button on my webpage that, when clicked, will trigger a playlist of randomly selected songs. Once pressed, this button should vanish, giving way to an audio control window that spans the full width of the screen at the bottom ...

What is the process for configuring my CSS and JS files to send HTTP response headers?

During our security evaluation of a web application built in Laravel 4, we discovered that the Anti-MIME-Sniffing header X-Content-Type-Options was not properly configured to 'nosniff'. The following PHP code snippet sets the necessary HTTP heade ...

Communication between React.js and Node.js in VS Code

I recently started learning React and node js. I managed to create a simple "Hello World" project in reactjs, which works perfectly. App.js import React, { Component } from 'react'; import logo from './logo.svg'; import './App.cs ...

Using Jquery and Ajax to add information to a database

One of the challenges I'm facing involves a page with three forms, each containing separate variables that need to be inserted into a MySQL database for viewing. My current script is working fine, even though I am aware that `mySql_` is deprecated but ...

React Material UI - All radio buttons within a list can be individually selected

I'm looking to create a set of Radio Buttons for each element in my array. While my project is functioning well overall, I'm having issues with the radio buttons as they are all selectable at once. ...

Add a Filter to the Observer (__ob__) in Typescript

I am trying to implement a filter using this.Grid.option("dataSource").filter(x => x.Placeholder != null) however, it doesn't seem to be working when I run console.log(this.Grid.option("dataSource")); I receive (72) [{…}, {…}, {…}, {†...

Access the id of an object in an array using Vue.js

Is there a way to showcase value data depending on the index array? I have created a modal for editing data, with a JSON structure like this: [ { "ID": 3, "idusers": 3, "skills": "Go", ...

Manipulating the .innerHTML property allows for selectively replacing sections

In my JavaScript code, I am trying to display a video along with a countdown timer. Once the countdown finishes, it should switch the content of the div to show a question. Below is my current implementation: <script type="text/javascript"> ...

Can someone please advise me on how to output the value of a var_dump for an array using console.log?

After writing the code in this manner, it functions properly and returns a JSON object. public function getElementsAction() { $currency = App::$app->getProperty('currency'); if(!empty($_POST)) { $sql = 'SELECT name, p ...

Understanding the distinction between assigning a value and setting text through JSE in Selenium using C#

Utilizing the IJavaScriptExecutor to set the attribute value can sometimes result in the text box containing the set value, but not displaying it as text. In some cases, the input is sent normally to certain text boxes, while for others, it is only setting ...

"Trouble arises with the match() function in relation to email regex validation

After retrieving the HTML content from a website with my function, I am using String.prototype.match along with a regex rule to extract email addresses from that page. However, the issue is that I am receiving a line that matches the regex but does not con ...

Updating props in a recursive Vue 3 component proves to be a challenging task

I am facing an issue with two recursive components. The first component acts as a wrapper for the elements, while the second component represents the individual element. Wrapper Component <template> <div class="filter-tree"> &l ...

Storing data in MongoDB using JavaScript on a web platform

Imagine a straightforward website with a common structure <html> <head></head> <body> <script type="text/javascript"> </script> </body> </html> Can data be written to MongoDB fr ...

Guide to importing an npm package into a client-side file

Having some trouble importing the js-search npm package into my client-side .js file. The documentation suggests using import * as JsSearch from 'js-search';, but I keep getting a Uncaught TypeError: Failed to resolve module specifier "js-se ...

What is the best time to fetch the height of an element containing an image?

I am working on my web app and I want to implement a popup element that contains an <img> element. Typically, the image source is larger than necessary, so I resize it using CSS. However, before displaying the popup, I need to determine its outerHeig ...

Implement Video Quality Controls for HLS.js and Video.js during Live Streaming

Exploring HLS.js (() => { var video = document.getElementById('video'); console.log('VIDEO', video); if (Hls.isSupported()) { var hls = new Hls(); hls.loadSource('https://te ...

How can I choose records from collection 'x' in mongodb?

I need to fetch all fields from my database using an API call Here is my code: exports.objfields = async (req, res, next) => { try { var db = mongo.connection; var objeto = req.headers.objeto; const result = db.db.collection(objeto).find( ...

Discover the largest possible value

With two arrays and a truck at my disposal, I'm tasked with determining how many units can fit in the truck. The arrays are as follows: boxes = [3, 1, 6] units_per_box = [2, 7, 4] truck_size = 6 Each box is of uniform size and the truck can accommoda ...