Reputation: 8711
Let's say I have an array, and an array of objects, each of which contain a reference to an element in the first array and a value to be inserted to the original array.
What will be the code to insert the desired value of the object in the second array, right after the referenced element in the first array?
For example, this is what I am trying to do:
const fruits = ["apple","melon", "banana", "kiwi"]
const colors = [{ref: "apple", color: "red"}, {ref: "banana", color:"yellow"}]
const result = ["apple", "red", "melon", "banana", "yellow", "kiwi"];
Thanks a lot in advance!
Upvotes: 1
Views: 72
Reputation: 50694
You could build a Map (colorMap
) which is keyed by ref
from your colors
array. The Map would would end up having the following structure:
{
"apple" => ["apple", "red"]
"banana" => ["banana", "yellow"]
}
As you can see, each key in the map is the fruit with it's associated array as its value. Once you have the colorMap
, you can use the .flatMap()
method on your fruits
array which will allow you to transform each element. If a fruit exists in the colorMap
, you can map the fruit to the elements stored in the fruits key, if it doesn't exist, you can take a default value of the fruit itself using || fruit
.
See example below:
const fruits = ["apple","melon", "banana", "kiwi"]
const colors = [{ref: "apple", color: "red"}, {ref: "banana", color:"yellow"}];
const colorMap = new Map(colors.map(({ref, color}) => [ref, [ref, color]]));
const res = fruits.flatMap(fruit => colorMap.get(fruit) || fruit);
console.log(res);
If you can't support .flatMap()
, then you can consider using a regular .map()
, and then flattening the array using .concat()
with the spread syntax:
const fruits = ["apple","melon", "banana", "kiwi"]
const colors = [{ref: "apple", color: "red"}, {ref: "banana", color:"yellow"}];
const colorMap = new Map(colors.map(({ref, color}) => [ref, [ref, color]]));
const res = [].concat(...fruits.map(fruit => colorMap.get(fruit) || fruit));
console.log(res);
Upvotes: 1
Reputation: 159
If the position of ref
and color
does not change
const insert = (fruits, colors) => {
const newFruits = result = JSON.parse(JSON.stringify(fruits));
const newColors = JSON.parse(JSON.stringify(colors));
newColors.forEach(element => {
let elem = Object.values(element);
newFruits.map((element, index) => {
if (element === elem[0]) {
result.splice(index+1, 0, elem[1])
}
})
});
return result;
}
Upvotes: 1
Reputation: 3345
The simplest solution is using the forEach loop .
const fruits = ["apple","melon", "banana", "kiwi"]
const colors = [{ref: "apple", color: "red"}, {ref: "banana", color:"yellow"}]
var result= [];
fruits.forEach(fruit => {
result.push(fruit);
colors.forEach(color => {
if(fruit === color.ref){result.push(color.color)}
});
});
console.log(result);
Upvotes: 1