5

I have a string with values like this a,b,c,d and want to remove a specific letter by index

So here is what I did str.split(',').splice(1,1).toString() and this is (obviously) not working since splice is returning the values removed not the original array

Is there any way to do the above in a one liner?

var str = "a,b,c,d";
console.log(str.split(',').splice(1,1).toString());

Thanks in advance.

2

4 Answers 4

5

You can use filter and add condition as index != 1.

var str = "a,b,c,d";
console.log(str.split(',').filter((x, i) => i != 1).toString());

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

3 Comments

Would you know in terms of performance, would this be faster then just doing it in 2 lines?
Filter is O(n) while splice is O(1). But performance differences in this simple case are really negligible.
Please review medium.com/@justintulk/… to know about performance. splice is definitely faster.
4

Another strange solution. Destructure the array, remove the unwanted index, get an object and join the values of it.

var string = "a,b,c,d",
    { 1: _, ...temp } = string.split(',')

console.log(Object.values(temp).join(','));

Comments

3

The alternate way using regex replace

var str = "a,b,c,d";

console.log(str.replace(/,\w+/, ''))

2 Comments

I tried to think of one, but I always add /g in my head :)
@mplungjan /g becomes a habit :)
2

Splice works in place, so oneliner is

const arr = "a,b,c,d".split(','); arr.splice(1,1); console.log(arr.toString());

If you want an string in a oneliner, you have to hardcode the index in a filter

console.log("a,b,c,d".split(',').filter((item, i) => i != 1).toString())

Or two slices (not performant at all)

const arr = "a,b,c,d".split(',')
console.log([...arr.slice(0,1),...arr.slice(2)].toString())

1 Comment

I guess you need to use semicolons instead of linebreaks - OP is asking for a one-liner :-)

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.