The behavior of JS Array.push may catch you off guard

There seems to be an issue with the push function in my code. The problem lies in the last line of code shown below.

export enum non_searchFieldsNames {
    language = 'language',
    categories = 'categories',
    subtitle = 'subtitle',
    publishedDate = 'publishedDate',
    id = 'id',
}
enum columnsEnum {
    title,
    authors,
    language,
    categories,
    subtitle,
    publishedDate,
}

function toArray(obj: header | contentCategories | sourceFields) {
    return Object.entries(obj)
        .sort((a, b) => {
            return +a - +b;
        })
        .map(item => item[1]);
}

let sourceFieldsObject: sourceFields = {
    [columnsEnum.title]: searchFieldsNames.title,
    [columnsEnum.authors]: searchFieldsNames.authors,
    [columnsEnum.language]: non_searchFieldsNames.language,
    [columnsEnum.categories]: non_searchFieldsNames.categories,
    [columnsEnum.subtitle]: non_searchFieldsNames.subtitle,
    [columnsEnum.publishedDate]: non_searchFieldsNames.publishedDate,
};

const sourceFieldsArray = toArray(sourceFieldsObject).push(non_searchFieldsNames.id);


The issue arises with the latest line of code. The value returned is 7. When I simplify the code like this:

const sourceFieldsArray = toArray(sourceFieldsObject)

I get an array (minus the additional value). Separating the logic into two lines:

const sourceFieldsArray = (toArray(sourceFieldsObject));
sourceFieldsArray.push(non_searchFieldsNames.id);

Yields the desired outcome. However, I prefer a one-liner solution. What could be causing this error? I also attempted:

const sourceFieldsArray (toArray(sourceFieldsObject)).push(non_searchFieldsNames.id)

Unfortunately, this did not resolve the issue.

Answer №1

push directly modifies the original array, and instead of returning a new array as anticipated, it provides you with the count of items in that array.

To see push's output value, you can refer to the demonstration below:

const array = [1,1,1] //3 items

const count = array.push(1) //1 additional item

console.log(count) //total of 4 items

If you prefer a concise solution, you may explore the cloning technique using the spread operator

const sourceFieldsArray = [...toArray(sourceFieldsObject), non_searchFieldsNames.id]

Note that this method involves creating an entirely new array, so it's important to be mindful of performance implications when dealing with large arrays.

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

The select2 does not show the selected information

My select2 is not selecting the value when in edit mode. You can view my data here. Upon clicking the edit data button, it should select "settings" as the parent's value, but unfortunately, it's not working. You can see the issue here. Modal Sc ...

Having trouble accessing the text in a paragraph using JavaScript executor and web driver

On a particular website, there is: <p id="tempid" value="Manual Effect">testing the test</p> String value = (String)((JavascriptExecutor) this).executeScript("return window.document.getElementById('tempid').value"); System.out.pr ...

What is the maximum string length allowed for the parameter accepted by JavaScript's JSON.Parse() function?

Is there a maximum string length limit for the parameter accepted by JavaScript's JSON.Parse()? If I were to pass a string that surpasses this expected length, will it result in an exception being thrown or prevent the function from returning a valid ...

Trigger a pop up using AJAX when successful

There is a button that, when clicked, triggers a pop up dialog box with the code below: <div class="button-wrap"><button data-dialog="somedialog" class="trigger">Open Dialog</button></div> The script responsible for activating the ...

How do I implement an onClick event for an antd message component?

I have a question and I'm hoping for some help. Here is the code snippet in question: const [msgTimer, setMsgTimer] = useState(5); message.error('some error msg', msgTimer); In the antd documentation, the message component has an onClic ...

The cURL command successfully executes the request, however, it fails to work in both Postman and web browsers

A problem arises when the Node Js (express) server responds to requests using cUrl, resulting in an infinite load. However, when requested via Postman or a browser, there are no errors but still faces issues. Despite searching for solutions, none of the s ...

Updating a Zendesk ticket with multiple comments

I've been attempting to update a ticket on Zendesk using their API and adding multiple comments. However, it seems that I might be utilizing the incorrect format as the comments are not showing up on my Zendesk dashboard... The JSON format I'm c ...

I need the language chosen using Lingui's Language Switcher (i18n) to persist throughout the app, even after a refresh

I have been experimenting with Lingui for internationalization (i18n) in my app. I followed the documentation and tutorial to create a language switcher, but I am unsure how to set it up so that the selected language persists throughout the app even after ...

Error message: "jQuery is not defined and occurs exclusively in Chrome."

I've been using the following code to asynchronously load my JavaScript in the head section: <script type='text/javascript'> // Add a script element as a child of the body function downloadJSAtOnload() { var element4= document.creat ...

One jQuery plugin was functioning perfectly, while the other one was failing to work as expected

I am working on a simple HTML file that includes a heading and two empty div elements. <h1>Blablabla.</h1> <div id="div1"></div> <div id="div2"></div> These two divs need to be populated with SVG content generated usin ...

The NodeJS application experiences a crash if incorrect parameters are provided to the API

Currently, I have built a CRUD API using TypeScript with Node.js, Express, and MongoDB. My goal is to ensure that the API functions correctly when the correct parameters are sent through a POST request. However, if incorrect parameters are passed, the Node ...

Leveraging Ajax for transmitting JSON data and performing decoding operations

Previously, I used an AJAX script to fetch data from viewCommentsJson.php. The data retrieved looked like this: [{"comments":"Greta"},{"comments":"John"}]. Is there a way to decode and display this return value properly? Appreciate any assistance. Gret ...

When the clearInterval function is invoked - either when the timer is modified or when the rendering is detached from the setInterval it is linked to

As a new React developer, I've come across a problem that has me stuck. Does the setInterval associated with a specific render get cleared automatically? import React, { useState, useEffect, useRef } from "react"; import ReactDOM from ...

Error occurs when incorporating OrbitalControl into Three.js leads to TypeError

Attempting to incorporate OrbitalControls into a Three.js Script to allow users to view two spheres in an empty space. However, upon running the code, the following error is encountered: three.js:5353 Uncaught TypeError: Cannot read property 'center& ...

Invoke the function when you finish typing in React.js

After I finish typing, I want to execute some code. I attempted to use the following script but it didn't work as expected const stopTypingHandler=(e)=>{ let time; clearTimeout(time); time = setTimeout(() => { console.log("click& ...

Discover how to capture a clicked word within the Ionic Framework

I've been working on an app using the Ionic Framework. I am trying to figure out how to detect when a word is pressed in my application. One solution I tried involved splitting the string into words and generating a span with a click event for each on ...

Trigger a page refresh using a popup

Exploring the world of React for the first time has been quite a journey. I've encountered a hurdle in trying to force my page to render through a popup window. The setup involves a function component with a popup window that allows text changes on t ...

Iterate through the array without obtaining the expected outcomes

I am currently utilizing a foreach loop to construct a grid within a table that contains data points from a racing series. Previously, I was using a while loop with the php mysql interface. However, I have now transitioned the entire site to use PDO. This ...

Enhance Image Size with a Custom React Hook

I've created a function to resize user-uploaded images stored in state before sending them to the backend. const [file, setFile] = useState(null) function dataURLtoFile(dataurl, filename) { let arr = dataurl.split(','), mime = arr[0].ma ...

Adjust the size and position of the text input field

I'm struggling to find a way to both resize and move the box without one action interfering with the other. Whenever I attempt to change the size of the box, it triggers the move event at the same time. Clicking on the box should make it resizable, bu ...