Skip to content
Advertisement

Convert JavaScript Array [a, b, c, d, e] into [a+b, b+c, c+d, d+e] dynamically

I have an array [a, b, c, d, e, .....] .

How can convert this like [a+b, b+c, c+d, d+e, ....]

The reducer may be the best way to do this but how to store temp memory after calculation. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Please check this code

function randomIntegerArray(length) {
  const random = Math.floor(
    Math.pow(10, length - 1) +
      Math.random() * (Math.pow(10, length) - Math.pow(10, length - 1) - 1),
  );
  return String(random).split('');
}
 const makeQuestions = (del, len) =>
    new Array(len)
      .fill(randomIntegerArray(del))
      .map((row, index) => {
      
      // row [a, b, c, d, e]
      // ans [a+b, b+c, c+d, d+e]
      let ans = [];
      
        return {
          question: row,
          answer: ans,
        };
      } );
      
      console.log(makeQuestions(5, 2));

Advertisement

Answer

There are some issues in your code:

  • The randomIntegerArray function can only deal with lengths up to about 17, … for greater values, it will keep producing zeroes beyond index 17. This is because of the precision limit that floating point has.

  • The randomIntegerArray function does not do what its name says: it produces an array of strings, not of integers

  • The randomIntegerArray function never produces a zero at index 0.

  • The randomIntegerArray function cannot produce numbers greater than 9.

  • Your code only generates one such random array, and then assigns that single array to several slots in your question array using fill. Although not clear from your question, it seems more likely you want to generate as many random arrays as you have “questions”.

Here is how you could do the job, also addressing the above mentioned issues:

const randomIntegerArray = (length, max=9) =>
    Array.from({length}, () => Math.floor(Math.random() * (max+1)));

const makeQuestions = (del, length) =>
    Array.from({length}, () => randomIntegerArray(del))
         .map((question, index) => ({
            question,
            anser: question.slice(0, -1)
                           .map((item, index) => item + question[index+1])
          }));
      
console.log(makeQuestions(5, 2));
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement