1

I create an array in this way:

const [...mg_dx] = [0, 2, 4].map(index => buf.readInt16LE(index));
this.arrayMgDx.push([this.timeS, ...mg_dx].join(":"))

where I put a timestamp and values.

The result is like this:

"-26416:393:333:574",
"-26336:393:332:573",
"-26296:393:332:573",
"-26296:395:333:574",
"-26276:396:333:574",
"-26236:396:332:574",
"-26216:396:332:576",

What I want to do is to change for the array the first value for every row (-26416,-26336,-26296...) starting from 0 and increment 20 for every row, like this:

"0:393:333:574",
"20:393:332:573",
"40:393:332:573",
"60:395:333:574",
"80:396:333:574",
"100:396:332:574",
"120:396:332:576",

How can I do it?

2
  • 3
    Thought you should know, const [...mg_dx] = array is identical to const mg_dx = array Commented Jan 8, 2020 at 14:58
  • you are right :) Commented Jan 8, 2020 at 14:59

3 Answers 3

7

You can use .map() for that:

const input = [ "-26416:393:333:574",
      "-26336:393:332:573",
      "-26296:393:332:573",
      "-26296:395:333:574",
      "-26276:396:333:574",
      "-26236:396:332:574",
      "-26216:396:332:576"]
      
const output = input.map((row, index) => {

  // array desctructuring here:
  // if we do sth like this:
  // const [first, ...parts] = [0, 1, 2, 3];
  // then `first` holds the first element of that array which is `0`
  // and the `parts` holds the rest of the array, which is `[1,2,3]`;
  // two techniques here: array destructuring and rest parameter
  const [first, ...parts] = row.split(':');
  return `${index * 20}:${parts.join(':')}`;
});

console.log(output);

Sign up to request clarification or add additional context in comments.

2 Comments

thank you for your answer, can you explain me about first and parts?
It's an array destructuring, I'll add a comment to explain
1

You could replace every value using the following regular expression.

/^-\d+/

let values = [
  "-26416:393:333:574",
  "-26336:393:332:573",
  "-26296:393:332:573",
  "-26296:395:333:574",
  "-26276:396:333:574",
  "-26236:396:332:574",
  "-26216:396:332:576"
]

console.log(values.map((value, index) => value.replace(/^-\d+/, index * 20)));

2 Comments

Thank you! A question, with this method I select only the first value when it is negative?? Because I'm interested both (plus or minus)
@Jack23 Just modify the pattern: /^([+-])?\d+/ to take an optional + or -.
1

You can use slice() and indexOf()

let arr = [
  "-26416:393:333:574",
  "-26336:393:332:573",
  "-26296:393:332:573",
  "-26296:395:333:574",
  "-26276:396:333:574",
  "-26236:396:332:574",
  "-26216:396:332:576"
];

console.log(arr.map( (str, i) => i*20 + str.slice(str.indexOf(':'), -1) ));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.