I have to convert two arrays into a single array base on given below condition. a= ["dry chapati", "dry chapati", "dry chapati"] b = ["chapati", "less fat", "no oil"];
I want to convert a and b to as below
c = ["dry chapati" : "chapati", "less fat", "no oil"]
I am trying it as below but not getting desired result as c
let recipe = ["dry chapati", "dry chapati", "dry chapati"];
let tags = ["chapati", "less fat", "no oil"];
let r = [];
for(let i=1; i<recipe.length; i ){
if(recipe[i] == recipe[i 1]){
recipe[i] = tags
// console.log(recipe);
}
}
Please help to find a solution.
CodePudding user response:
let recipe = ["dry chapati", "dry chapati", "dry chapati"];
let tags = ["chapati", "less fat", "no oil"];
let array3 = [...new Set(recipe.concat(tags) )];
console.log(array3);
CodePudding user response:
let arr1 = ["dry chapati", "dry chapati", "dry chapati"];
let arr2 = ["chapati", "less fat", "no oil"];
const merge = (arr1, arr2) => {
const res= [arr1[1]];
arr1.forEach((arr,i) =>
res.push(`${arr2[i]}`)
);
return res;
}
console.log(merge(arr1,arr2));
CodePudding user response:
Just use merge
$a1=array("red","green"); $a2=array("blue","yellow"); print_r(array_merge($a1,$a2));
CodePudding user response:
Try using the spread syntax.
let recipe = ["dry chapati", "dry chapati", "dry chapati"];
let tags = ["chapati", "less fat", "no oil"];
let result = [...recipe, ...tags];
let result2 = [];
result2.push(...new Set(result));
console.log(result2);
This will give you the result you want.
CodePudding user response:
You question is not clear as what you want to achieve but according to my understanding of the problem. Give below are two possible ways.
/*If you want to achieve something like
let c = [{'dry chapati': 'chapati'}, {'dry chapati': 'less fat'}, {'dry chapati': 'no oil'} ]
*/
let thirdArray = [];
for (let i = 0; i < recipe.length; i ) {
let dish = {
[recipe[i]]: tags[i],
};
thirdArray.push(dish);
}
/*If you want to achieve something like
let c = [{'dry chapati': ['chapati', 'less fat', 'no oil']}. {...}]
*/
let fourthArray = [];
for (let i = 0; i < tags.length; i ) {
let secondDish = {
[recipe[i]]: [tags],
};
fourthArray.push(secondDish);
}
CodePudding user response:
You can use LINQ. Zip in jQuery, you can add (https://github.com/multiplex/multiplex.js) LINQ library JS in your script file and try this code.
var arr1 = [1, 2, 3, 4]; var arr2 = ["A", "B", "C", "D"];
var res = arr1.zip(arr2, function(a, b){ return {Num:a, Letter:b} });