1

I have the following code.

var eqn = c1 + q1 + q2 +  ‘ + ‘ + c2 + w1 + w2 + ‘=‘ + c3 + e1 + e2;

This code combines strings not add numbers.

I think it would be best to modify this string by using an array which I can do. My question is I want to remove the variable if it equals 1. For example if c1 == 1 then the variable should be defined like this: var eqn = q1 + q2 + ‘ + ‘ + c2 + w1 + w2 + ‘=‘ + c3 + e1 + e2; I want this to happen to any one or more variable that is equal to one. Is there a function or piece of code that can be used to do this?

8
  • 1
    @GeorgeJempty Sorry my mistake, take a look at the updated question Commented Nov 23, 2017 at 1:30
  • 2
    This will produce a syntax error.. Commented Nov 23, 2017 at 1:33
  • @webdeb What do you mean? Commented Nov 23, 2017 at 1:39
  • 1
    there is + operator missing, and btw. what are you doing? concatenating stirngs or adding numbers? If this is a mix, it will end up in an unexpected result: 2 + 2 + " + " + 3 + 3 check your console.. Commented Nov 23, 2017 at 1:41
  • 1
    Use parentheses to make it clear and better readable: (2 + 2) + " + " + (3 + 3) Commented Nov 23, 2017 at 1:42

3 Answers 3

3

You can use Array.reduce

var string = [c1, q1, q2, ' + ', c2, w1, w2, ' = ', c3, e1, e2]
  .reduce((acc, cur) => cur == 1 ? acc : acc + '' + cur, '');

Example:

The following values

1 + 2 + 3 + ' + ' + 4 + 5 + 6 + ' = ' + 7 + 8 + 9;

will return

'23 + 456 = 789'
Sign up to request clarification or add additional context in comments.

8 Comments

Very pretty! But maybe make sure you coerce it to a string or c1 and q1 will add mathematically. ...? acc : '' + acc + cur
@klugjo Does that mean when I run console.log(string); will I get one fluent string?
That's nice! I would have filtered then joined. I like your method though.
would't it be prefixed with "undefined", you should probably define the initial acc.
@klugjo q1, w1, and e1 are letters/words, would this method still work?
|
0

OK so under the assumption that the variables are numeric you could run them all through a function such as the following, which will return zero if it contains one, and the arithmetic will work out:

function excludeIfOne(val) {
    return val === 1 ? 0 : val
}

This could however lead to one long messy line of code. See the other answer suggesting the use of reduce, which I was about to suggest myself

Comments

0

If you are not familiar with reduce, you can using filter and join.(likes klugjo's way)

var string = [c1, q1, q2, ' + ', c2, w1, w2, '+', c3, e1, e2];
string.filter(word=> word!=1).join('');

2 Comments

typo: use filter instead of map
Thanks for indicating my fault.

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.