简体   繁体   中英

Remove a given value from a string along with comma in Javascript

I am trying to remove a set of given values from a string of comma separated values as follows:

// mainString

mainString = '1,2,3,4,5'

// Values to subtracted from mainString

givenValuesString1 = '1'

givenValuesString2 = '2,3'

givenValuesString3 = '5'

givenValuesString4 = '3,5'

// Desired Output Values

desiredOutput1 = '2,3,4,5'

desiredOutput2 = '1,4,5'

desiredOutput3 = '1,2,3,4'

desiredOutput4 = '1,2,4'

What I tried is this:

desiredOutput =  mainString.replace(givenValuesString, '')

desiredOutput =  mainString.replace(`${givenValuesString},`, '')

My problem is that when I try the second method, value without a comma after it is not deleted ie, the last character in the mainString. Another problem is I am not able to delete the values if they are one after another ie, values like 2,4 or 3,5 .

Values remaining if I use the above two methods:

// First method

desiredOutput1 = ',2,3,4,5'

desiredOutput2 = '1,,4,5'

desiredOutput3 = '1,2,3,4,'

desiredOutput4 = '1,2,3,4,5'

// Second method

desiredOutput1 = '2,3,4,5'

desiredOutput2 = '1,4,5'

desiredOutput3 = '1,2,3,4,5'

desiredOutput4 = '1,2,3,4,5'

So how can I achieve the desired result? ie, the given values along with the comma must be deleted from the mainString and also even if they are not adjacent to each other.

Just use a Map or Set to do it. If you want order, then Map . Otherwise Set . Since you mentioned you don't need the order, I have used Set to do it.

 mainString = '1,2,3,4,5' givenValuesString1 = '1' givenValuesString2 = '2,3' givenValuesString3 = '5' givenValuesString4 = '3,5' function subtract(main, s) { let set = new Set(main.split(",").map(a => Number(a))); s.split(",").map(a => Number(a)).forEach(a => set.delete(a)) return Array.from(set).join(",") } console.log(subtract(mainString, givenValuesString1)); console.log(subtract(mainString, givenValuesString2)); console.log(subtract(mainString, givenValuesString3)); console.log(subtract(mainString, givenValuesString4));

Actually, even if using Set , if you don't do a set1 - set2 kind of operation, you can keep the order:

 mainString = '1,2,3,4,5' givenValuesString1 = '1' givenValuesString2 = '2,3' givenValuesString3 = '5' givenValuesString4 = '3,5' function subtract(main, s) { let set = new Set(s.split(",").map(a => Number(a))); return main.split(",").filter(a => !set.has(Number(a))).join(",") } console.log(subtract(mainString, givenValuesString1)); console.log(subtract(mainString, givenValuesString2)); console.log(subtract(mainString, givenValuesString3)); console.log(subtract(mainString, givenValuesString4));

In general, you'd avoid any method that uses O(n²) time complexity (the ones above are not). That's because if the main string is 1,000,000 entries and the "removal" string is 500,000 entries, you'd be look at 1,000,000 x 500,000 = 500,000,000,000 steps (roughly speaking, in that order of magnitude).

You can try this:

var mainString = "1,2,3,4,5";
var givenString ="2,3";

var strarr = mainString.split(",");
var givarr = givenString.split(",");

var output = strarr.filter(function(val){
    return !givarr.includes(val);
});

var desiredOutput = output.join(',');

You can use the following:

 const mainString = "1,2,3,4,5"; const givenValuesString1 = "1"; const givenValuesString2 = "2,3"; const givenValuesString3 = "5"; const givenValuesString4 = "3,5"; const removeFromCsv = (values, filterValues) => values .split(",") .filter(v => !filterValues.split(",").includes(v)) .join(","); console.log( removeFromCsv(mainString, givenValuesString1), // 2,3,4,5 "-", removeFromCsv(mainString, givenValuesString2), // 1,4,5 "-", removeFromCsv(mainString, givenValuesString3), // 1,2,3,4 "-", removeFromCsv(mainString, givenValuesString4) // 1,2,4 );

Use string.split() function to convert your string to array, then iterate to remove the elements, then use array.join() function to convert the resulting array back to string.

 // mainString var mainString = '1,2,3,4,5' // Values to subtracted from mainString var givenValuesString1 = '1' var givenValuesString2 = '2,3' var givenValuesString3 = '5' var givenValuesString4 = '3,5' // Desired Output Values var desiredOutput1 = '2,3,4,5' var desiredOutput2 = '1,4,5' var desiredOutput3 = '1,2,3,4' var desiredOutput4 = '1,2,4' var arr1 = mainString.split(",") console.log("arr1") console.log(arr1) var arrToBeDeleted1 = givenValuesString1.split(",") console.log("arrToBeDeleted1") console.log(arrToBeDeleted1) var arrOutput1 = arr1.slice() // copy the array console.log("arrOutput1") console.log(arrOutput1) for(var i = 0; i < arrToBeDeleted1.length; i++) { var toBeDeleted1 = arrToBeDeleted1[i] var index1 = arr1.indexOf(toBeDeleted1) console.log("index1") console.log(index1) arrOutput1.splice(index1, 1) console.log("arrOutput1") console.log(arrOutput1) } console.log(arrOutput1.join(","))

I have achieved this by using string .split() and by filtering the array.

Here is the code :

 function processStr(data){ var mainStr = "1,2,3,4,5" var arrStr = mainStr.split(',') var filteredArr = arrStr.filter(function(obj) { return data.indexOf(obj) == -1; }); var result = filteredArr.toString(); return result } var str1 = processStr('1,2,3') var str2 = processStr('1') var str3 = processStr('2,3') var str4 = processStr('1,4') console.log(str1) console.log(str2) console.log(str3) console.log(str4)

Let me know if it helps you

in your case you have 2 input parameters :

  1. main string like '1,2,3,4,5'
  2. blacklist like '2,4'

and you want a string as a result that include main string numbers without numbers in blacklist
see, explain is easier.

so I offer this way :

// first define your variables
let main = '1,2,3,4,5';
let blacklist = '3,4';

// now let's make result
let result = main
            .split(',') // split function make an array from your string with delimiter coma => [1,2,3,4,5]
            .filter( // filter function is a simple loop that decrease array with your condition
                 item => blacklist.indexOf(item)==-1 // if current item is in black list ignore it
            )
            .join (','); // and finaly join array elements with coma to make result as string

console.log(result); //tada , it is what you need => '1,2,5'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM