Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
I have two arrays.
var addFrom = ["orange", "banana", "watermelon", "lemon", "peach"];
var addTo = ["pear", "tangerine", "grape", "orange", "blueberry"];
I would like to check if the first item in "addFrom" array is already in "addTo" array.
If the "addTo" array does not have the first item in "addFrom" array, I would like to push this item to "addTo" array.
However, if the first item in the "addFrom" array is already in the "addTo" array, I would like to move on to the second item in the "addFrom" array and do the same thing until I find the item in the "addFrom" array that is not in the "addTo" array, which will then be pushed to the "addTo" array. and I want to add only one item to the "addTo" array.
As a result, I want the "addTo" array to look like this:
var addTo = ["pear", "tangerine", "grape", "orange", "blueberry", "banana"];
How can I do this in JavaScript?
You could use Array#some()
and stop the iteration if one item is not in the addTo
array.
var addFrom = ["orange", "banana", "watermelon", "lemon", "peach"],
addTo = ["pear", "tangerine", "grape", "orange", "blueberry"];
addFrom.some(function (a) {
if (!~addTo.indexOf(a)) {
addTo.push(a);
return true;
}
});
document.write('<pre> ' + JSON.stringify(addTo, 0, 4) + '</pre>');
A simple loop seems the best approach here (I've used while
).
var i = -1, len = addFrom.length;
while (++i < len) {
if (addTo.indexOf(addFrom[i]) === -1) {
addTo.push(addFrom[i]);
break;
}
}
DEMO
var addFrom = ["orange", "banana", "watermelon", "lemon", "peach"];
var addTo = ["pear", "tangerine", "grape", "orange", "blueberry"];
for(var i = 0; i < addFrom.length; i++){
if(addTo.indexOf(addFrom[i]) === -1 ){
addTo.push(addFrom[i]);
break;
}
}
https://jsfiddle.net/povvx8hg/
var addFrom = ["orange", "banana", "watermelon", "lemon", "peach"];
var addTo = ["pear", "tangerine", "grape", "orange", "blueberry"];
for (i = 0; i < addFrom.length; i++) {
if(addTo.indexOf(addFrom[i]) != -1) {
console.log("Exist");
} else {
addTo.push(addFrom[i]);
}
}
console.log(addTo);
Easy peasy
for (index = 0; index < addFrom.length; ++index) {
if (addTo.indexOf(addFrom[index]) === -1){
addTo.push(addFrom[index]);
break;
}
}
You can use forEach
var addFrom = ["orange", "banana", "watermelon", "lemon", "peach"];
var addTo = ["pear", "tangerine", "grape", "orange", "blueberry"];
var inserted = false;
addFrom.forEach(function(v,i){
if(inserted)
return;
if(addTo.indexOf(v)<0)
{
addTo.push(v);
inserted = true;
}
})