Returning spliced elements will yield a nested array

I'm currently working on a script that involves selecting 3 random items from an array and storing them in a new array. To achieve this, I'm utilizing the splice() method to extract an item from the original array. However, when I attempt to add these items to the new array using push(), the items are being stored as nested arrays rather than a single array.

Here's an example scenario:

["b", "f", "a"]

This is my current code implementation:

const letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
let newletters = [];

for (let i = 0; i < 3; i++) {
    newletters.push(letters.splice(Math.floor(Math.random() * letters.length), 1));
}

console.log(newletters);

It appears that the spliced items are being added to the new array as subarrays. Is there a way to address this issue?

[
  [
    "b"
  ],
  [
    "f"
  ],
  [
    "a"
  ]
]

Answer №1

To extract elements from an array, you can use the spread syntax or the Array#splice method.

Alternatively, you can access the first element using its index.

letters.splice(Math.floor(Math.random() * letters.length)[0]

const letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
let newletters = [];

for (let i = 0; i < 3; i++) {
    newletters.push(...letters.splice(Math.floor(Math.random() * letters.length), 1));
}

console.log(newletters);

Answer №2

Why not try using the Array.prototype.concat function?

const fruits = ['apple', 'orange', 'banana', 'grape', 'kiwi'];
let newFruits = [];

for (let i = 0; i < 3; i++) {
    newFruits = newFruits.concat(fruits.splice(Math.floor(Math.random() * fruits.length), 1));
}

console.log(newFruits);

Answer №3

Employ the ... spread operator within the push function.

const numbers = [1, 2, 3, 4, 5];
const newNumbers = []
newNumbers.push(...numbers.slice(1, 3)) // Results in newNumbers containing [2, 3]
console.log(newNumbers)

Answer №4

const alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
let randomLetters = [];

for (let i = 0; i < 3; i++) {
    randomLetters.push(alphabet.splice(Math.floor(Math.random() * alphabet.length), 1));
}

console.log(randomLetters.flat());

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 challenges encountered with JSONP/Ajax Script - displaying 'Undefined'

I need help retrieving data from a webserver that I don't have control over. I've searched online but haven't found a solution yet. I've tried various codes, with and without DataTables. If anyone could provide guidance on where to go ...

Incorporating Javascript into a <script> tag within PHP - a step-by-step guide

I am trying to integrate the following code into a PHP file: if (contains($current_url, $bad_urls_2)) { echo '<script> $('body :not(script,sup)').contents().filter(function() { return this.nodeType === 3; ...

PHP array_key_exists - flexible on certain data types, stringent on others

Despite my decent knowledge of PHP quirks, I found myself puzzled by the unexpected behavior demonstrated in the code below today: // loose $a = array(true => 'foo'); var_dump(array_key_exists(1, $a)); // strict $a = array('7.1' =& ...

Embracing the node mindset with a Java foundation

As a Java Developer, I have become accustomed to working in a sequential manner where tasks are executed one after the other or concurrently with multiple threads. The organization of code in a sequential way seemed logical under this paradigm. However, wh ...

Injecting script into a webpage and initiating an ajax request prior to receiving a response

Trying to accomplish something a bit complex that I believe is feasible, or perhaps someone could offer a suggestion on how to achieve it. At website A, there is a database containing booking data. At website B, the goal is to display information about w ...

What is the best way to transmit JSON data to a Web API?

As I work on developing a website with web API integration, I encountered an issue while trying to send JSON data to my controller. Multiple actions were found that match the request: Post on type AuctionWebsiteASP.Controllers.MovesController readDatab ...

Implement tooltip functionality in ssr chart using echarts

A chart is generated using echarts on the server-side: getChart.ts const chart = echarts.init(null, null, { renderer: 'svg', ssr: true, width: 400, height: 300 }); chart.setOption({ xAxis: { data: timeData }, ...

Maintain user authentication in Firebase as long as the localStorage object remains active

I am currently working on an app using Ionic, Angular2, and Firebase. My approach involves saving the auth.currentUser information in the localStorage when a user logs in or registers. However, I recently discovered that having the user variable set in th ...

Adding missing values to two corresponding arrays in JavaScript

I am working with two arrays: xAxisData: ["0006", "0007", "0009", "0011", "0301"] yAxisData: [6.31412, 42.4245, 533.2234, 2345.5413, 3215.24] My goal is to standardize the length of the xAxis array to a maximum value, for example, DATAPOINT_LENGTH_STAND ...

What could be the reason for this simple sails socket not functioning properly?

Just curious why the simple web socket code below isn't functioning? io.socket.on('user', function(event){ console.log("RECEIVED EVENT:",event); }) I have included sails.io.js in my index file and the above code is located in a test.js ...

Unable to retrieve a specific property from a JSON object in JavaScript

I am working with a JSON object and encountering an issue. alert(typeof object) //Output Object Upon using the JSON.stringify method, I receive the following string: alert(JSON.stringify(object)); //Output object [{ "locationId":"8", "locationTypeId" ...

Avoid reactivating focus when dismissing a pop-up menu triggered by hovering over it

I am currently utilizing @material-ui in conjunction with React. I have encountered the following issue: In my setup, there is an input component accompanied by a popup menu that triggers on mouseover. Whenever the menu pops up, the focus shifts away from ...

Inject Angular environment variables into compiled static Angular files within a Spring Boot application

Currently, I am utilizing Angular and Spring Boot for the development of a website project. During deployment, we execute the command ng build --output-path=../spring-boot-project/src/main/resources/static" in Angular to generate a static folder withi ...

Canvas drawImage function not displaying image at specified dimensions

I'm having trouble loading an image into a canvas using the drawImage function. Additionally, I've implemented drag functionality but found that when moving the image inside the canvas, it doesn't follow the mouse cursor in a linear manner. ...

When a change is made in the parent component, the local state of the child component in ReactJS is automatically updated

I'm currently facing a challenge while implementing a custom dropdown filter for a table in react. Each column has a set of dropdown values with an Apply button. To handle this, I've created a child component that takes the dropdown values and s ...

Embed a subcomponent within another component triggered by an onClick event in ReactJS

Watch this quick demo to see my project in action. So, here's the deal - I have a menu with different options, and when "Tickers" is selected, I want it to display the Tabs component. However, if any other menu option is chosen, I don't want the ...

Utilize an array-variable in VBA to maximize the effectiveness of your SQL WHERE clause

Is there a way to insert an array, stored in a variable, into the WHERE clause of a SQL statement in VBA? recordset1.Open "SELECT * FROM [Table] WHERE [NettingSet] = '" & varRecord & "'" The original string is: recordset1.Open "SELECT ...

Cherrypy/Chrome: Issue with jquery ajax request remaining pending after several successful requests

My current project involves a Cherrypy server that receives a JSON array from a client via AJAX call. The server then manipulates the array and sends it back to the client. However, I've noticed an issue where after a few smooth requests, the next req ...

What could be causing my function to fail after pressing the button?

I am new to coding in HTML and JS and attempted to create a button that combines two strings into one when clicked. Can someone please review my code and point out where I may have made an error? <!DOCTYPE html> <html> <body> ...

Is it advisable to approve automatic pull requests initiated by dependabot for updating the yarn.lock file?

I've recently received some pull requests from "dependabot" in a JavaScript library I am working on, like the one found here. While I appreciate the effort to update dependencies to newer versions, it seems strange that each PR only updates the versi ...