A single element in an array, a string labeled "magically," mysteriously transforms into a standalone string

Uncertain of the reason for this issue. In this part of my code, these arrays might contain only a single element.

actualAnswer = actualAnswer.split(" ");
playerAnswer = playerAnswer.split(" ");

Next, I put them through this function.

function checkForPlural(playerAnswer, actualAnswer){

var answerObject = {playerAnswer: playerAnswer,
                    actualAnswer: actualAnswer};

for (var answerWord in actualAnswer){
    if (actualAnswer[answerWord].slice(-1) == "S")
    {
            answerObject.actualAnswer[answerWord] = actualAnswer[answerWord].substring(0, actualAnswer[answerWord].length - 1);
    }
}
for (var answerWord in playerAnswer){
    if (playerAnswer[answerWord].slice(-1) == "S")
    {
            answerObject.playerAnswer[answerWord] = playerAnswer[answerWord].substring(0, playerAnswer[answerWord].length - 1);
    }
}
}

Upon returning the object, if the passed arrays had just one element, Javascript interprets them as strings. Therefore, using answerObject.actualAnswer.length would provide the length of the string instead of 1.

Link to the functioning Plunker: https://plnkr.co/edit/nIqq3VdjjMa2GDWyqkxx

UPDATE: Found that the issue was actually in an earlier part of my code. Apologies!

Answer №1

To transform elements in an array, utilize Array.prototype.map(). Use String.prototype.replace() to replace the last character "S" in a string if present. Return an object with properties assigned to function parameter identifiers.

const pattern = /S$/;
const replacement = "";

function modifyElements(array, pattern_, replacement_) {
  return array.map(function(element) {return element.replace(pattern_, replacement_)})
}

function analyzePlurals(userInput, correctAnswer) {
  return {
    userInput: modifyElements(userInput, pattern, replacement),
    correctAnswer: modifyElements(correctAnswer, pattern, replacement)
  }
}

console.log(analyzePlurals("abc defS ghi".split(" "), "12S 456 78S".split(" ")))

Answer №2

Everything appears to be functioning properly, the unexpected transformation occurred as a result of a flaw in a separate function that was replacing the array with a string. Apologies for the confusion.

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 best way to combine two vertex positions using a distance-based blending technique relative to the camera's position?

My goal is to achieve a smooth transition between two different vertex positions based on the distance from the camera. Specifically, I aim to create a visual effect that seamlessly shifts between a horizontal plane near the camera and a vertical plane in ...

Incorporating TypeScript basics into the if statement post compiling

As I delve into the Angular2 Quickstart, I stumbled upon a peculiar issue within app.component.js after compiling app.component.ts using tsc (version 1.8.2): if (d = decorators[i]) I am unable to pinpoint where I may have gone wrong in configuring the qu ...

Connecting a text input in a nested component to the data passed down from its parent component in VueJS

My VueJS setup involves a child component sending data to a parent component, which then tries to route the data to a sibling of the child to create new components. I'm using a dictionary to group the data and push it into an array. The array is then ...

Creating a forEach statement in an express.js router to handle JSON data

I need help creating an API that will generate a JSON output containing the names extracted from the forEach loop. There are 8 names being processed and I can only use res.send once. See the code snippet below: timeSeries.forEach(data => { res.js ...

Defining array size in C++ for Windows Driver Kit

Could someone clarify if the term "header" is accurate in this context? I am attempting to allocate memory and then utilize an overloaded placement new[] operator to create an array of class objects (let's say, MyClass). Assuming a MyClass object si ...

PHP and AJAX enable the seamless transfer of large files to a server in chunks via remote upload. This process includes a time limit setting to ensure efficient

Over on StackOverflow, there's a thread dedicated to the topic of streaming large files to users in chunks. The answer provided includes code that demonstrates how to accomplish this. However, my focus is on figuring out a way to simply save the file ...

Pressing the Enter key will result in data fetched from JSON being logged multiple times

I am currently implementing a search feature on my React website. When a user enters a keyword in the search input, the keyword is matched in a JSON file. If a match is found, it logs "yes" to the console; otherwise, nothing is logged. Here is an example ...

What is the best way to approach this regular expression task?

I need help with a jQuery/Javascript task involving a string. There are 2 things I need to accomplish: Remove all characters (numbers, symbols, etc.) before the first alphabetic character (a-zA-Z). Save the removed string in one variable and save the res ...

Merging SCSS and CSS into a unified file using WebPack

Trying to grasp webpack as a beginner is proving to be quite challenging for me. I'm struggling with the concept of merging multiple scss and css files together using webpack, after transpiling the sass. Unlike gulp, where I could easily transpile sa ...

Extract latitude and longitude coordinates from a dataset by applying a rectangular filter

I have developed a program that extracts information from a JSON object and showcases it on a webpage, specifically focusing on Public Bike Stations. The JSON object includes the latitude and longitude of each station, making it easy to locate them. My cu ...

Ways to verify the presence of an element in a list

I found this interesting JS code snippet: ;(function ($) { $('.filter-opts .opt').click(function(){ var selectedName = $(this).html(); $('.append').append('<li>' + selectedName + '</li> ...

What is the best way to merge different Vue JS instances (each linked to different html divs) into one cohesive unit using Vue

Essentially, I have a scenario where I've created two HTML divs named vueapp1 and vueapp2. Both of these divs serve the same purpose of displaying information and are linked to their individual Vue instances for extracting JSON data and presenting it. ...

Is there a way to programmatically simulate clicking on the "Cancel search" button?

I have a text input field with type "search". In order to perform UI testing, I need to simulate clicking on the "cancel search" button: https://i.sstatic.net/ahcwQ.png The code for this specific input field is as follows: <input type="search" value= ...

Choosing a particular 2D array based on another variable in jQuery and JavaScript

Within my project, I am utilizing 2D arrays to append specific divs under particular circumstances. In an effort to streamline and enhance the code, I attempted to create a variable that would determine which array to utilize based on the id of an HTML < ...

Difficulties arising when trying to convert latitude and longitude coordinates to xyz for camera rotation within Three.js

Currently, I am working on a JavaScript application that allows users to design their own closet. My goal is to enable smooth rotation of the closet without changing the distance from the camera to the closet. While it would be simple to rotate the object ...

Exploring the concept of pointer dereferencing in variables and arrays within the C programming language

I'm a little puzzled when it comes to pointers. In the code I'm using, there are two pointers that work correctly, but I don't fully understand why they work. The first one is char *note = "A7"; The second one is char *octFreq[15] = ...

Collapse of divs occurring during jQuery sortable sorting process

I'm facing a challenge with a list that can be dynamically added to and deleted from. The length of the list can vary. My goal is to implement jQuery sortable for this list, but I want only the Customized Details to be sortable. These specific detail ...

Using Puppeteer in Javascript to locate text on a webpage

I am currently exploring ways to utilize Puppeteer for searching an HTML page for a specific product name. Just to give you an idea, the HTML code looks something like this: <a class="example" href = "example_link">PRODUCT NAME&l ...

Unzipping a .gz file in node.js: a simple guide

I have downloaded a .csv.gz file from a remote server, and I have the content of this file stored as a string. When I console.log it, here is a small sample of what it looks like: }v)tYj8p0eCR l1=6~̵r0c77LU:0g How can I decompress this in Node.js and c ...

What steps can I take to ensure that only one panel is opened or expanded at any given time?

Introducing a versatile component/function that showcases a expandable card feature triggered by a button. The <Viewmore> component serves as an image placeholder, essential for SVG images utilization. import React, { useState, useRef } from "re ...