1

I have a large array of strings in the format PRODUCTCODE1-QTY,PRODUCTCODE2-QTY,...,PRODUCTCODEN-QTY

I need to replace all the product codes with new product code retaining the existing QTY with the high optimised fastest code.

The expected result is

"1234-2,1234-2"
""
""
""
"1234-2"
"1234-2,1234-2"
"1234-4"
"1234-4,1234-4"

The given strings are

"22543-2,25543-2"
""
""
""
"2543-2"
"2543-2,2543-2"
"2543-4"
"25543-4,25743-4"

I have tried with

var strings = str.split(",")
    for(i=0;i<strings.length;i++)
    {
    var q = ''; 

        var qty = string.split("-")[1]
        result.push("1234-"+qty)
    }
    r = result.join(",")
1
  • 2
    You don't seem to be checking if you are actually having that existing product code or not. What's the problem you are having with your current code? Also, when you replace the existing product codes, you have then a line left with "1234-2,1234-2". Shouldn't it be "1234-4" then? Seeing that you just have two lines with the same product code? Commented Sep 22, 2019 at 14:55

3 Answers 3

3

You could use regex:

var data = [
"22543-2,25543-2",
"",
"",
"",
"2543-2",
"2543-2,2543-2",
"2543-4",
"25543-4,25743-4"];

var replaced = data.map(function(e){
  return e.replace(/(^|,)\d+-/g, "$1"+"1234-")
});
console.log(replaced);

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

3 Comments

Could you help me to code without using the operator =>
I actually need this to implement using google apps script, which doesnt support => operator
@CodeGuy Done.
2

You can do it by using regular expressions, and Array#map():

const input = [
  "22543-2,25543-2",
  "",
  "",
  "",
  "2543-2",
  "2543-2,2543-2",
  "2543-4",
  "25543-4,25743-4"
]
const replacement='1234'

const result=input.map(e => e.split(',').map(e => e.replace(/\d+/,replacement)).join(','))

console.log(result)

3 Comments

since he doesn't care about the product code, couldn't you just split with - sign versus the regex as well? (not sure what would be faster though)
Could you help me to code without using the operator =>
@CodeGuy => creates an arrow function (x=>y almost equivalent to (function(x){return y})). Read more here
2

I've updated a bit your current solution:

function codeUpdater(oldString, codeBase){
  var strings = oldString.split(",");
  var updatedArray = [];
  for(var i=0;i<strings.length;i++){
      var string = strings[i];
      var qty = string.split("-")[1];
      string = codeBase + '-' + qty;
      updatedArray.push(string);
  }
  return updatedArray;
}

console.log(codeUpdater('2537-2, 2534-2, 2537-1, 2537-4', 1234));

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.