1

I have two JavaScript array.

var arrOne = ["1.", "2.", "3.", "4.", "5."];
var arrTwo = ["3.4", "1.1", "2.3", "1.5", "10", "2.4" , "44"];

For every item in first array (arrOne), I want to check how many items from second array (arrTwo) contains values starting with the value from first array.

Ex: I will check how many items in arrTwo starts with value "1.". It should return me "1.1", 1.5.

After I find these values I want to replace 1 with 1.1 & 1.5 in the first array.

So the final output should look like: ["1.1", "1.5", "2.3", "2.4", "3.4", "4.", "5."];

I know how to find the values but not sure to replace the values .

4
  • 1
    Out of curiosity, why string values? There seems to be a solution that would consist of numeric comparison and addition rather than string comparison. Commented May 13, 2014 at 12:38
  • Does it have to replace values in arrOne or is creating a new array acceptable? Commented May 13, 2014 at 12:41
  • @Cory: I want to manipulate array of dimension attribute from SSAS. But to explain the question better I showed numeric values as string. Commented May 13, 2014 at 12:43
  • looks like a homework Commented May 13, 2014 at 12:55

2 Answers 2

3

You can use two loops, checking the index of the arrOne element within arrTwo. If a match exists, add it to the final array of values. Something like this:

var arr = [];
$.each(arrOne, function (i, val) {
    var valFound = false;
    $.each(arrTwo, function (i, v) {
        if (v.indexOf(val) == 0) {
            valFound = true;
            arr.push(v);
        }
    });
    !valFound && arr.push(val);
});

Example fiddle

Alternatively in native JS only:

var arr = [];
for (var i = 0; i < arrOne.length; i++) {
    var valFound = false;
    for (var n = 0; n < arrTwo.length; n++) {
        if (arrTwo[n].indexOf(arrOne[i]) == 0) {
            valFound = true;
            arr.push(arrTwo[n]);
        }
    };
    !valFound && arr.push(arrOne[i]);
};

Example fiddle

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

1 Comment

Thank you for quick reply. I should have mentioned in my question that I don't want to introduce a third array. Is it possible to achieve this result without another array??
0

You can try this:

var arrOne = ["1.", "2.", "3.", "4.", "5."];
var arrTwo = ["3.4", "1.1", "2.3", "1.5", "10", "2.4" , "44"];

var arrResult = [];

for (var i = arrOne.length - 1; i >= 0; i--) {
    for (var x = arrTwo.length - 1; x >= 0; x--) {
        if(arrOne[i] == arrTwo[x].substring(0,arrOne[i].length)) {
            arrResult.push(arrTwo[x])
        }
    };
};

console.log(arrResult);

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.