Merging together two arrays results in a cohesive sentence

Just starting out with javascript and struggling to merge arrays. I attempted to reverse words manually, but ended up with unexpected results. Here is the code snippet:

function reverseString(kata) {
  let currentString = kata;
  let newString = '';
  let cetakKata = '';
  for (let i = kata.length - 1; i >= 0; i--) {
    newString = newString + currentString[i];
  }
  console.log(newString);

  const splitNewString = newString.split(' ')
  console.log(splitNewString);

  for (let i = 0; i < splitNewString.length; i++) {
    const cetak = splitNewString[i].split('').reverse().join('')
    cetakKata = cetakKata + cetak
  }
  console.log(cetakKata);
}
reverseString('hello java script');

Here is my current output:

scriptjavahello

The desired output is:

script java hello

Answer №1

function ReverseWordsInString (inputString) {
  return inputString.split(" ").reverse().join(" ");
}

ReverseWordsInString("I become Stronger each day")

Answer №2

How to reverse a string without using the built-in method

reverseString('hello world');

function reverseString(sentence) {
  let splitWords = sentence.split(' ');
  let reversedWords = [];
  for (let j = 0; j < splitWords.length;j++) {
    reversedWords.push(splitWords[(splitWords.length - 1) - j ]);
  }
  let reversedString = reversedWords.join(' ');
  console.log(reversedString);
}

Answer №3

If you’re eager to delve into the world of JavaScript, it seems like that’s exactly why you’re tackling it the way you are. However, there are pre-existing functions available that can achieve what you’re attempting.

arr.reverse() // reverses array

It’s hard to say how many programming languages you’ve grasped, but personally, I find it most effective to thoroughly review all documentation so I’m aware of the tools at my disposal. I might not retain everything, but I’ll recognize them when seeking out solutions.

https://developer.mozilla.org/en-US/docs/Learn/JavaScript

function reverseString(kata) {
  const AT_SPACE = ' ';
  
  return kata
  .split(AT_SPACE)
  .reverse()
  .join(AT_SPACE);
}

let reversedKata = reverseString('hello java script');
console.log(reversedKata)

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

Attempting to access the 'name' field from an input element in an HTML document using AngularJS, and also introducing a static field named 'likes' with a value

Currently, I am in the process of developing an application that retrieves a list of Beers from an API. Each beer in the JSON response contains the fields {name: "beer", id: number, likes: number}. However, I am facing a challenge while attempting to add ...

Froala - response in JSON format for uploading images

I have integrated the Froala editor into my website. The image upload feature of this editor is functioning properly, but I am facing issues with the response. As per the documentation provided: The server needs to process the HTTP request. The server mu ...

Conceal Navigation Panel while Scrolling Down, Reveal when Scrolling Up, Compatible with Chrome, Incompatible with Safari (on smartphones

I have implemented a code to hide my navbar when scrolling down and show it when scrolling up. This code works perfectly on desktop and in all browsers, including Chrome on mobile (iPhone). However, in Safari, the navbar sometimes shows, hides, and shows a ...

Converting a nested array of doubles into a string in Swift: tips and tricks

I am struggling with converting an array of arrays filled with doubles into a single string that I can print to the console. I need to write a function that accepts an array of arrays of doubles as input and returns a string object. The goal is to loop thr ...

Dynamically delete a property from a JSON object

I am currently working on a task that involves removing properties from a JSON object. I need to create a system where I can specify an array of locations from which the fields should be redacted. The JSON request I am dealing with looks like this: { "nam ...

Is there a better option than using public methods when transitioning from class-based to function-based React components?

When working with React components that utilize hooks, they must be function-based rather than class-based. I've encountered a challenge transitioning from calling methods on child components in class-based components to achieving the same functionali ...

UI-data contracts: enhancing client-side JSON data validation

I have encountered situations where the JSON data I receive from services and database calls, created by a different team, contains invalid data combinations that lead to unintended errors downstream. For example, in the case below, if the "rowContent" fi ...

Tips on verifying the count with sequelize and generating a Boolean outcome if the count is greater than zero

I'm currently working with Nodejs and I have a query that retrieves a count. I need to check if the count > 0 in order to return true, otherwise false. However, I am facing difficulties handling this in Nodejs. Below is the code snippet I am strugg ...

Tips for styling text in a mailto function

I am working with two arrays and an object in my project. The first array contains product codes, while the second array contains the quantities of each product. The quantities array corresponds to the product codes array, meaning the first quantity in the ...

Enhancing validation in an established tutorial using Backbone

After following Thomas Davis' tutorial, I decided to enhance the age field by adding validation. However, my attempts to modify the Model as shown below have been unsuccessful: var User = Backbone.Model.extend({ validate: function(attr, error) { ...

Resolving the Challenge of PHP's Unique MultiDimensional Arrays

Currently, I am extracting distinct values from my multidimensional array by employing the subsequent function: function unique_multidim_array($array, $key) { $temp_array = array(); $i = 0; $key_array = array(); ...

Using NodeJS and ExpressJS to send the HTTP request response back to the client

After creating a website using Angular 2 and setting up node.js as the backend, I successfully established communication between the Angular client and the node.js server. From there, I managed to forward requests to another application via HTTP. My curren ...

Implementing the Tab key functionality without redirecting to the address bar

I recently integrated a Tab control into my project, but I'm encountering an issue where pressing the Tab key causes the address bar to jump when I try to press another key. This only happens after the Tab key functions correctly in the scene. How can ...

Determine the exact scroll position needed to reveal the element when scrolling in reverse

I'm looking for a way to make my div disappear when I scroll down and reappear immediately when I start scrolling back up. Currently, it only works when I reach a certain position instead of taking effect right away. I need assistance in calculating t ...

Is it possible to center align a div without specifying the width?

After doing some research, it appears that the solution to my issue is not very promising. I want to avoid using a table for this particular case. My menu consists of 6 'a element' inline-blocks, which look great except for the fact that their wi ...

When a legend is clicked, it should display only the selected item while hiding all other legends automatically in a chart created

I have a highchart with 10 legends. When I click on the first legend, only that legend should remain visible while the rest are automatically hidden... Below is a code snippet with two legends: $(function() { var chart = $('#container').hig ...

Retrieve a distinct set of values from one column depending on the values in another column

In order to streamline our software inventory process, I have compiled a comprehensive list of applications running on all assets such as servers, notebooks, and desktops. The table consists of two columns - Column A contains the names of every asset, whil ...

Tips for inserting a personalized image or icon into the ANTD Design menu

Can anyone help me figure out how to replace the default icons with a custom image or icon in this example: https://ant.design/components/layout/#components-layout-demo-side I attempted to do it by including the following code: <Menu.Item to="/" key=" ...

Synchronous CORS XHR encounters issues with 302 redirect, while asynchronous function successfully redirects

Why does Firefox seem to be the only browser that doesn't throw an error when performing a synchronous request? Any insights on this peculiar behavior? // Ensure your JS console is open when running this script var url = '//api.soundcloud.com/ ...

Do not execute the script if the window's width is below a certain threshold

I have a unique website layout that adjusts to different screen sizes, and I've incorporated some jQuery functionality. Here is a snippet of the code: <script> $(document).ready(function(){ $("#D1000C36LPB3").click(function(){$("#D ...