What is the procedure for modifying two consecutive values in an array based on a specific condition?

I am attempting to insert a dash between even numbers in an array taken from an input. My approach involves using the reduce() method combined with a specific condition that compares two consecutive iterations. Since I am new to programming, it would be great if the solution is simple and easy to understand for me... :)

Although I realize this code snippet does not work as intended, the idea is clear. For example, when given "12534487" as input, I would like the output to be "12534-4-87".


          ar = prompt("numberInput").split("");
          ar.map(x => parseInt(x));
          ar.addDashToEven();
          const addDashToEven = (a, b) => {
            for (a % 2 == 0 && b % 2 == 0) {
              a = a + "-"
            }
          }
       
     

Answer №1

To convert a string into a new string with certain criteria applied, you can split and map through the characters of the string while checking conditions like whether the previous character is even or odd.

In this method, a destructuring assignment is used to access the index of the current character along with a variable representing the previous character.

{ [i - 1]: l }

var string = '124568',
    result = string
        .split('')
        .map((r, i, { [i - 1]: l }) => (l % 2 === 0 && r % 2 === 0 ? '-' : '') + r)
        .join('');

console.log(result);

Answer №2

Try solving this without using any built-in array methods.

const numString = "12534487";
const numArr = numString.split('');

for(let j = 0; j < numArr.length; j++){
  if(numArr[j] % 2 === 0 && numArr[j+1] % 2 === 0){
    numArr[j] = numArr[j] + '-';   
  }
}

console.log(numArr.join(''))

Answer №3

You were so close! To access the previous value, simply add parameters to your map function such as index and originalArray.

console.log(
  "12534487".split("")
  .map((val, index, originalArray) => {
    const prev = originalArray[index - 1];
    return prev !== undefined && !(val % 2) && !(prev % 2) ? "-"+val : val;
  })
  .join("")
)

Alternatively, you can use regular expressions for a more intuitive solution:

console.log(
  "125343424324443487".replace(/([02468])(?=[02468])/g, '$1-')
)

Answer №4

To implement the use of reduce, follow this example:

const numbers = [1, 2, 3, 4, 4, 4, 5, 6, 6, 9];

const result = numbers.reduce((accumulator, currentValue) => {
  if ((accumulator[accumulator.length - 1] % 2 == 0 || typeof accumulator[accumulator.length - 1] === "string") && currentValue % 2 == 0) {
    accumulator[accumulator.length - 1] += "-" + currentValue;
    return accumulator;
  } else {
    accumulator.push(currentValue);
    return accumulator;
  }
}, []);

console.log(result);

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

Navigating through images via opacity changes in HTML

Is there a way to create a smooth transition effect between pictures in HTML without reloading the page? I have a series of images that I want users to navigate through by clicking a "Next" button, and I would like each image to fade into the screen. Are ...

How can I adjust the column width in OfficeGen?

Currently, I am utilizing officeGen for the purpose of generating word documents. <sup> let table = [ [ { val: "TT", fontFamily: "Times New Roman", }, { val: "Ten hang", ...

Ways to implement the Run function prior to any controller execution

Currently, I am exploring AngularJS to develop my very first application. My main goal is to ensure that the run function is executed before any controller. Here's a snippet of my run function: .run(function ($rootScope, authentification) { ...

How can I determine if a value in a JavaScript object is null or empty?

Here is the issue I am facing: I have an array of objects like the one below: [{ "name": "Alex", "code": "05422180283", "pIva": "05422180283", "subCode": null }, { "name": "John", "code": null, "pIva": null, "subCode": "IT" ...

Calculating discounts using Vue.js: A step-by-step guide

I am working with a basic database that contains several fields including id, product_name, original_price, and discount. The discount field is specified in percentage format. To populate all the data at once using Axios and display it on the page using v ...

Transform a text node into an HTML element with the help of JQuery

Consider this HTML snippet: <div> Lorem ipsum <span>dolor sit</span> amet <span>consectetur adipiscing elit</span> eiusmod tempor </div> To select the text nodes [Lorem ipsum, amet, eiusmod tempor], ...

Tips for ensuring that an HTTP request receives a response before moving on to the next step in Angular 7

I am currently developing an app where I need to make a GET request to retrieve data from a component. The issue I am facing is that the next step in the process is being executed before I receive a response from the service. Below is my service file: ...

Unfortunately, I am unable to transmit a cookie using the res.cookie method in Express

After setting up the route to send a JWT with a cookie, I'm unable to see it in my browser. Here's the code for the route: router.post('/signup', async (req, res) => { const { email, password } = req.body try { const ...

Implementing a dynamic module or dependency addition using a webpack plugin: A comprehensive guide

I'm feeling a bit frustrated because what I am trying to accomplish doesn't seem too difficult, but the documentation for webpack is so disorganized that it's eating up a lot of my time. Can someone please explain how I can inject a "dynami ...

Tips for building a sleek vertical carousel website

Looking to set up a sleek vertical carousel for my product list, specifically for a Kiosk Machine that utilizes touchscreen technology. I want the carousel to be smooth and scrollable. I'm a bit unsure about which library or tools to use for this pro ...

Pass data stored in a PHP array from a PHP file to a JavaScript array in a JS file

I am currently working on passing an array ($phpArray) from a PHP file to a function in a JS file (data.js). I'm having trouble figuring out the right approach. Any ideas? dataInput.php (PHP File) <?PHP $phpArray=[[1,2,3,4,5], [2,3,5,6 ...

The dropdown menu button stubbornly remains open and refuses to close

Having an issue with a dropdown menu button where it should open when clicked on the icon and close when clicking off the icon or on the icon again, but instead, it remains open. Here is a screenshot for reference: https://i.stack.imgur.com/UX328.jpg I&a ...

Is it possible to use Typescript to store and access static global variables based on a unique key

I want to store variables in a static global file, like this: declare const MYVAR = 'Some unchanging data'; Later on, I would like to be able to retrieve the information using just the key 'MYVAR', for example: globalFile.findValue ...

How to save the value of `this.$route.params.id` in a Vue.js data property?

I am currently working with Vue.js 3 and have a sample code for routing and passing parameters. Below is the Home.vue page: <template>   <div class="home">     <h1>       All Destinations     </h1>     < ...

vaadin-grid selection issue not functioning

I'm encountering an issue with the row selection feature. The selectedItems array only updates when I select all items at once. I'm not sure if I'm missing something or if this is a bug. selectedItems: An array that contains the selected ...

npm command syntax to accept multiple arguments

Struggling to pass arguments in an npm command and utilize them in my script For instance: npm run test -b chrome -e QA "scripts": { "test": "something.js ./xyz/abc/cdf --something \"{\\\"browser\\\": \&bsol ...

Is it possible to modify the appearance or behavior of a button in a React application based on its current state?

I'm looking to customize the color of a button based on different states. For example, if the state is active, the button should appear in red; otherwise it should be blue. Can anyone suggest how this can be achieved in React? Furthermore, I would als ...

Transferring information from JavaScript file to an HTML document

Learning the basics of NodeJS. I have created a simple program that sends data back and forth between HTML and NodeJS files. In my index.html file, there is a form for user input and a div to display the response from server.js: <html> <body> ...

Ways to insert a line break within a Json format

I am having trouble breaking lines to display text on the next line, despite using the nbreak variable I also tried using "//n" instead of assigning a variable but it didn't work. Can anyone help me figure out what I'm missing? function GetOrgJS ...

How do I incorporate a standalone checkbox in a React Material-UI table without affecting row selection upon clicking?

I would like to have a distinction between clicking on a checkbox and clicking on a row. Specifically, I want the following behavior: when I click on the checkbox, only the checkbox should be checked; and when I click on the row, only the row should be se ...