0

I have an array with text strings:

var myarray = ["valueA","valueB","valueC","valueD/valueA","valueE","valueC/valueA"];

Some of the values in the array have a slash, e.g. "aaa/bbb". The slash have a special meaning of separating two values.

I want to get a new array with one value or the other based on a boolean function.

For example:

var myarray = ["valueA/valueB"];
var myNewarray = myFunction(myarray, true); // myNewarray == ["valueA"]
var myNewarray2 = myFunction(myarray, false); // myNewarray2 == ["valueB"]

myarray = ["valueA/valueC","valueB","valueD/valueF"];
myNewarray = myFunction(myarray, true); // ["valueA","valueB","valueD"]
myNewarray = myFunction(myarray, false); // ["valueC","valueB","valueF"]
2
  • Does the fiddle link have anything to do with your question?! Commented Nov 17, 2014 at 14:41
  • Yes i want chose value with time if i have even week i chose value 1 if odd i chose value 2 ( myarray = [value1/value2]) Commented Nov 17, 2014 at 14:44

3 Answers 3

1

Use Array.map to call a function on each item and return another value depending on some conditions.

var cond = false;
var myarray = ["valueA/valueC","valueB","valueD/valueF"];
var myNewarray = myarray.map( function(item){
    var values = item.split('/');
    if( values.length == 2 ){
        return cond ? values[0] : values[1];
    }
    else {
        return item;
    }
});

http://fiddle.jshell.net/duw99072/

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

Comments

1

Just loop through your array and .split() on the slash if the element contains it:

Assuming you want the value of oddWeek (in your fiddle) to determine the left/right value of the slash-separated array elements:

var myarray = ["valueA/valueC","valueB","valueD/valueF"];
myarray.forEach(function (val, index, array) {
    if (val.indexOf('/') > -1) {
        val = val.split('/')[oddWeek];
    }
    output += '<p>' + val + '</p>'
});

Updated fiddle: http://fiddle.jshell.net/r1hvbjs5/2/

Comments

1

You could use Array.prototype.map - it creates a new array with the results of calling a provided function on every element in this array.

Considering your variable is named condition:

myarray.map(function(el){
 return el.indexOf('/') > -1 ? el.split('/')[condition ? 0 : 1] : el;
});

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.