Reputation: 19183
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 .
Upvotes: 1
Views: 113
Reputation: 616
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);
Upvotes: 0
Reputation: 337570
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);
});
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]);
};
Upvotes: 3