Rename object keys in cartesian output - javascript

Sorry for the bad question title, couldn't figure a better one.
I have this array of options:
const options = [
{
display_name: "Size",
_id: "1",
values: [
{
label: "Small",
_id: "1"
},
{
label: "Extra Large",
_id: "2"
}
]
},
{
display_name: "Colors",
_id: "2",
values: [
{
label: "Red",
value: "#ff0000",
_id: "3"
},
{
label: "Green",
value: "#00ff21",
_id: "4"
},
]
}
];
I run this function against it to get Cartesian Product:
const getCartesian = object => {
return Object.entries(object).reduce(
(r, [key, value]) => {
let temp = [];
r.forEach(s =>
(Array.isArray(value) ? value : [value]).forEach(w =>
(w && typeof w === "object" ? getCartesian(w) : [w]).forEach(x =>
temp.push(Object.assign({}, s, { [key]: x }))
)
)
);
return temp;
},
[{}]
);
};
This will result in an array of objects in the following format (console.log output):
[{0: Object, 1: Object}, {0: Object, 1: Object}, ...]
The desired output is:
[
{
"option":{
"id":1,
"display_name":"Size"
},
"value":{
"label":"Small",
"id": 1
}
},
{
"option":{
"id":2,
"display_name":"Color",
},
"value":{
"id":5,
"label":"Red"
}
}
...
]
here's the playground and what I've tried so far: https://codesandbox.io/s/8nvwm76nnj

You need to map() at the end to convert array to object.
const options = [
{
display_name: "Size",
_id: "1",
values: [
{
label: "Small",
_id: "1"
},
{
label: "Extra Large",
_id: "2"
}
]
},
{
display_name: "Colors",
_id: "2",
values: [
{
label: "Red",
value: "#ff0000",
_id: "3"
},
{
label: "Green",
value: "#00ff21",
_id: "4"
},
]
}
];
const getCartesian = object => {
let t = Object.entries(object).reduce(
(r, [key, value]) => {
let temp = [];
r.forEach(s =>
(Array.isArray(value) ? value : [value]).forEach(w =>
(w && typeof w === "object" ? getCartesian(w) : [w]).forEach(x =>
temp.push(Object.assign({}, s, { [key]: x }))
)
)
);
return temp;
},
[{}]
);
return t.map(({0:val1,1:val2}) => ({option:val1,arr:val2}))
};
console.log(getCartesian(options));

You could wrap the array in an object with a property option. This gives you later an array with objects with option as key for the cartesian product.
const getCartesian = object => {
return Object.entries(object).reduce(
(r, [key, value]) => {
let temp = [];
r.forEach(s =>
(Array.isArray(value) ? value : [value]).forEach(w =>
(w && typeof w === "object" ? getCartesian(w) : [w]).forEach(x =>
temp.push(Object.assign({}, s, { [key]: x }))
)
)
);
return temp;
},
[{}]
);
};
const options = [{ display_name: "Size", _id: "1", values: [{ label: "Small", _id: "1" }, { label: "Extra Large", _id: "2" }] }, { display_name: "Colors", _id: "2", values: [{ label: "Red", value: "#ff0000", _id: "3" }, { label: "Green", value: "#00ff21", _id: "4" }] }];
console.log(getCartesian({ option: options }));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

Show ID of Duplicate Values in Array of Object

I found here this code and works good. But I also need to know the "id" which is multible in use. e.g. in another array
var data = [
{"id":"1","Group":"Wohnzimmer","Light":"Diele", "type":"ct"},
{"id":"1","Group":"Wohnzimmer","Light":"Diele", "type":"ct"},
{"id":"2","Group":"Wohnzimmer","Light":"Diele", "type":"bri"},
{"id":"3","Group":"Wohnzimmer","Light":"Diele", "type":"color"},
{"id":"3","Group":"Wohnzimmer","Light":"Diele", "type":"color"},
]
var a = data.reduce((accumulator, current) => {
if (checkIfAlreadyExist(current)) {
return accumulator;
} else {
return [...accumulator, current];
}
function checkIfAlreadyExist(currentVal) {
return accumulator.some((item) => {
return (item.id === currentVal.id &&
item.Light === currentVal.Light &&
item.type === currentVal.type);
});
}
}, []);
console.log(a);
Reduced (it works fine!):
[{
Group: "Wohnzimmer",
id: "1",
Light: "Diele",
type: "ct"
}, {
Group: "Wohnzimmer",
id: "2",
Light: "Diele",
type: "bri"
}, {
Group: "Wohnzimmer",
id: "3",
Light: "Diele",
type: "color"
}]
Now, I need also the result of the deleted objects, like the following:
[{
Group: "Wohnzimmer",
id: "1",
Light: "Diele",
type: "ct"
},{
Group: "Wohnzimmer",
id: "3",
Light: "Diele",
type: "color"
}]
You can do this efficiently in linear time:
let key = obj => [obj.id, obj.Light, obj.type].join('##')
let seen = new Set,
unique = [],
removed = []
for (let obj of data) {
let k = key(obj);
(seen.has(k) ? removed : unique).push(obj)
seen.add(k)
}
use array.prototype.map and array.prototype.some
var values = [
{ name: 'someName1' },
{ name: 'someName2' },
{ name: 'someName4' },
{ name: 'someName2' }
];
var valueArr = values.map(function(item){ return item.name });
var isDuplicate = valueArr.some(function(item, idx){
return valueArr.indexOf(item) != idx
});
console.log(isDuplicate);
Using you current logic you could archive your preferred output with small changes, use a object instead with two arrays instead.
var data = [
{ id: "1", Group: "Wohnzimmer", Light: "Diele", type: "ct" },
{ id: "1", Group: "Wohnzimmer", Light: "Diele", type: "ct" },
{ id: "2", Group: "Wohnzimmer", Light: "Diele", type: "bri" },
{ id: "3", Group: "Wohnzimmer", Light: "Diele", type: "color" },
{ id: "3", Group: "Wohnzimmer", Light: "Diele", type: "color" },
];
var { unique, removed } = data.reduce(
(accumulator, current) => {
if (checkIfAlreadyExist(current)) {
return {
...accumulator,
removed: [...accumulator.removed, current],
};
} else {
return {
...accumulator,
unique: [...accumulator.unique, current],
};
}
function checkIfAlreadyExist(currentVal) {
return accumulator.unique.some((item) => {
return (
item.id === currentVal.id &&
item.Light === currentVal.Light &&
item.type === currentVal.type
);
});
}
},
{
unique: [],
removed: [],
}
);
console.log("Unique");
console.log(unique);
console.log("Removed");
console.log(removed);
Just create another array to store deleted items and if checkIfAlreadyExist returns true push current into the array.
var data = [
{"id":"1","Group":"Wohnzimmer","Light":"Diele", "type":"ct"},
{"id":"1","Group":"Wohnzimmer","Light":"Diele", "type":"ct"},
{"id":"2","Group":"Wohnzimmer","Light":"Diele", "type":"bri"},
{"id":"3","Group":"Wohnzimmer","Light":"Diele", "type":"color"},
{"id":"3","Group":"Wohnzimmer","Light":"Diele", "type":"color"},
]
var deleted = []
var a = data.reduce((accumulator, current) => {
if (checkIfAlreadyExist(current)) {
deleted.push(current)
return accumulator;
} else {
return [...accumulator, current];
}
function checkIfAlreadyExist(currentVal) {
return accumulator.some((item) => {
return (item.id === currentVal.id &&
item.Light === currentVal.Light &&
item.type === currentVal.type);
});
}
}, []);
console.log(a);
console.log(deleted)

Merge 2 objects in an array where the values are an array

I am trying to merge values in 2 objects from the same array. The objects in this case are similar and the values I want to merge are arrays(Set)
var array = [
{
name: "foo1",
value: ["val1","val2"]
},
{
name: "foo1",
value: ["val2", "val3"]
},
{
name: "foo2",
value: ["val4"]
},
{
name: "foo2",
value: ["val4","val5"]
},
];
Expected Output
[
{
name: "foo1",
value: ["val1","val2", "val3"]
},{
name: "foo2",
value: ["val4","val4", "val5"]
}
]
My Code
var output = [];
array.forEach(function(item) {
var existing = output.filter(function(v, i) {
return v.name == item.name;
});
if (existing.length) {
var existingIndex = output.indexOf(existing[0]);
let newValue = new Set(output[existingIndex].value).add(item.value)
output[existingIndex].value = Array.from(newValue);
} else {
output.push(item);
}
});
Output Gotten
[ {
name: "foo1",
value: ["val1", "val2", ["val2", "val3"]]
}, {
name: "foo2",
value: ["val4", ["val4", "val5"]]
}]
How can I get the expected output (ES6 would also be preferred)
Try this
const array = [
{
"name": "foo1",
"value": [
"val1",
"val2",
"val3"
]
},
{
"name": "foo1",
"value": [
"val2",
"val3"
]
},
{
"name": "foo2",
"value": [
"val4",
"val5"
]
},
{
"name": "foo2",
"value": [
"val4",
"val5"
]
}
]
const result = []
for (const item of array) {
const existingItem = result.find(i => i.name === item.name)
if (existingItem) {
existingItem.value = [...new Set([...existingItem.value, ...item.value])]
} else {
result.push(item)
}
}
console.log(result)
Is this code solve your problem?
var array = [
{
name: "foo1",
value: ["val1","val2"]
},
{
name: "foo1",
value: ["val2", "val3"]
},
{
name: "foo2",
value: ["val4"]
},
{
name: "foo2",
value: ["val4","val5"]
},
];
var output = [];
array.forEach(function(item) {
var existing = output.filter(function(v, i) {
return v.name == item.name;
});
if (existing.length) {
var existingIndex = output.indexOf(existing[0]);
let newValue = new Set(output[existingIndex].value.concat(item.value))
output[existingIndex].value = Array.from(newValue);
} else {
output.push(item);
}
});
try
var arr = [
{
name: "foo1",
value: ["val1","val2"]
},
{
name: "foo1",
value: ["val2", "val3"]
},
{
name: "foo2",
value: ["val4"]
},
{
name: "foo2",
value: ["val4","val5"]
},
];
var arr2={}
arr.map((elem,ind)=>{
if(!arr2[elem.name]){
arr2[elem.name]=[]
}
arr2[elem.name]=[...arr2[elem.name],...elem.value]
})
arr=Object.keys(arr2);
arr.map((elem,ind)=>{
arr[ind]={name:elem,value:arr2[elem]};
})
You can do the following using reduce,
var array = [
{
name: "foo1",
value: ["val1","val2"]
},
{
name: "foo1",
value: ["val2", "val3"]
},
{
name: "foo2",
value: ["val4"]
},
{
name: "foo2",
value: ["val4","val5"]
},
];
res = array.reduce((prev, curr) => {
let index = prev.findIndex(item => item.name === curr.name);
if(index > -1) {
s = new Set([...prev[index].value, ...curr.value]);
prev[index].value = Array.from(s);
} else {
prev.push(curr);
}
return prev;
},[]);
console.log(res);
You could use reduce method with a Map as accumulator value and then use spread syntax ... on Map values to get an array of values.
var array = [{"name":"foo1","value":["val1","val2","val2","val3"]},{"name":"foo1","value":["val2","val3"]},{"name":"foo2","value":["val4","val4","val5"]},{"name":"foo2","value":["val4","val5"]}]
const map = array.reduce((r, { name, value }) => {
if (!r.has(name)) r.set(name, { name, value })
else r.get(name).value.push(...value)
r.get(name).value = [...new Set(r.get(name).value)]
return r;
}, new Map)
const result = [...map.values()]
console.log(result)
One approach is to create an unique list of keys and iterate over it. Create an array for each key and merge the values. The vanilla js way is:
Array.from(new Set(array.map(el => el.name)))
.map(name => ({
name,
value: Array.from(new Set(array.filter(el => el.name === name).flatMap(el => el.value)))
}))
Example:
const array = [
{
name: "foo1",
value: ["val1","val2"]
},
{
name: "foo1",
value: ["val2", "val3"]
},
{
name: "foo2",
value: ["val4"]
},
{
name: "foo2",
value: ["val4","val5"]
},
];
console.log(Array.from(new Set(array.map(el => el.name)))
.map(name => ({
name,
value: Array.from(new Set(array.filter(el => el.name === name).flatMap(el => el.value)))
})));
Using lodash you can reduce it to
_.uniq(array.map(el => el.name))
.map(name => ({
name,
value: _.uniq(array.filter(el => el.name === name).flatMap(el => el.value))
}))
Example:
const array = [
{
name: "foo1",
value: ["val1","val2"]
},
{
name: "foo1",
value: ["val2", "val3"]
},
{
name: "foo2",
value: ["val4"]
},
{
name: "foo2",
value: ["val4","val5"]
},
];
console.log(_.uniq(array.map(el => el.name))
.map(name => ({
name,
value: _.uniq(array.filter(el => el.name === name).flatMap(el => el.value))
})));
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.20/lodash.min.js"></script>
Find unique values of keys. Match this keys within array and return unique objects. Push this objects in an empty array. Then match other objects value with the new arrays objects value and push the unmatched values to this new array.
var arr = [
{
name: "foo1",
value: ["val1","val2"]
},
{
name: "foo1",
value: ["val2", "val3"]
},
{
name: "foo2",
value: ["val4"]
},
{
name: "foo2",
value: ["val4","val5"]
},
];
let key = [];
arr.map((val)=>key.push(val.name));
let uniquekeys = [...new Set(key)]; //unique values of keys
let newarr = [];
uniquekeys.map((uniquekey,ind)=>{
let reduceunique = arr.filter((vals)=>uniquekey == vals.name); // return matching objects as array
newarr.push(reduceunique[0]); // Push unique objects in an empty array
for(let i = 1; i<uniquekeys.length;i++){
reduceunique[i].value.map((val)=>{
let existvalue = newarr[ind].value.indexOf(val); // Match every value with the unique objects values
if(existvalue<0){
newarr[ind].value.push(val); // push the unmatched value in the array
}
});
};
});
console.log(newarr);
try to use Array.reduce and Array.filter to get the result like the following
var array = [
{
name: "foo1",
value: ["val1","val2"]
},
{
name: "foo1",
value: ["val2", "val3"]
},
{
name: "foo2",
value: ["val4"]
},
{
name: "foo2",
value: ["val4","val5"]
},
];
res = array.reduce((prev, curr) => {
let index = prev.findIndex(item => item.name === curr.name);
if(index > -1) {
prev[index].value = [...prev[index].value, ...curr.value];
prev[index].value = prev[index].value.filter((v,i) => prev[index].value.indexOf(v) === i)
} else {
prev.push(curr);
}
return prev;
},[]);
console.log(res);

Reduce array of objects with deeply literals keys in JS

I'm confused about array transform with reduce method. I can't figure out how to deal with nested object with literal keys.
To brings some advantage, I'll post some example I'm wrote and it work fine:
// consider flat array of objects
const names = [
{ name: "Jaden", sname: "Smith", age: 33 },
{ name: "Will", sname: "Smith", age: 12 },
{ name: "Jada", sname: "Smith", age: 29 },
{ name: "Jose", sname: "Varho", age: 21 },
{ name: "Josephina", sname: "Varho", age: 44 },
{ name: "Keanu ", sname: "Reeves", age: 44 }] ;
// suppose i need to transform that array to this shape:
/* {
"Smith": {
"Jaden": 33,
"Will": 12,
"Jada": 29
},
"Varho": {
"Jose": 21,
"Josephina": 44
},
"Reeves": {
"Keanu ": 44
}
}
*/
// this reducer do it's fine:
const shapeIt = (acc, item) => {
console.log('acc:', JSON.stringify(acc));
acc[item.sname] = { ...acc[item.sname], [item.name]: item.age }
return acc
}
const transformShape= (arr) => {
return arr.reduce((acc, item) => shapeIt(acc, item), {});
}
transformShape(names); //gives required shape
So now, let's imaging i have more complex array like:
const flatArray = [
{ "blockId": "first-block", "sectionId": "first-section", "fieldId": "_1", "value": "0" },
{ "blockId": "first-block", "sectionId": "first-section", "fieldId": "_2", "value": "1" },
{ "blockId": "first-block", "sectionId": "second-section", "fieldId": "_1", "value": "1" },
{ "blockId": "second-block", "sectionId": "first-section", "fieldId": "_1", "value": "1" },
{ "blockId": "second-block", "sectionId": "some-section", "fieldId": "_2", "value": "3" },
{ "blockId": "third-block", "sectionId": "other-section", "fieldId": "_1", "value": "3" }];
// and i strictly need to get this shape of object:
/* {
"first-block": {
"first-section": {
"_1": "0",
"_2": "1"
},
"second-section": {
"_1": "1"
}
},
"second-block": {
"first-section": {
"_1": "1"
},
"some-section": {
"_2": "3"
}
},
"third-block": {
"other-section": {
"_1": "3"
}
}
}
*/
At this moment I'm write this kind of reduce function. It works but it gives me only last fieldId keys of each section in block. if section in one block have more than one fieldId - it lose it. I'm watch for a accumulator, and see that only keys with different blockId, sectionId is accumulated, but not different fieldId's.
const shapeComplex = (acc, item) => {
console.log('acc:', JSON.stringify(acc));
acc[item.blockId] = { ...acc[item.blockId], [item.sectionId]: { [item.fieldId]: item.value } }
return acc
}
const transformComplex = (arr) => {
console.log('initialArr: ', arr)
return arr.reduce((acc, item) => shapeComplex(acc, item), {});
}
transformComplex(flatArray);
// it gives me shape with only last idField in same section and block:
/*
{
"first-block": {
"first-section": {
"_1": "0"
},
"second-section": {
"_1": "1"
}
},
"second-block": {
"first-section": {
"_1": "1"
},
"some-section": {
"_2": "3"
}
},
"third-block": {
"other-section": {
"_1": "3"
}
}
}
*/
Any help, please.
You could take an array of wanted keys for grouping and take either the value or a new object for the next level.
const
data = [{ blockId: "first-block", sectionId: "first-section", fieldId: "_1", value: "0" }, { blockId: "first-block", sectionId: "first-section", fieldId: "_2", value: "1" }, { blockId: "first-block", sectionId: "second-section", fieldId: "_1", value: "1" }, { blockId: "second-block", sectionId: "first-section", fieldId: "_1", value: "1" }, { blockId: "second-block", sectionId: "some-section", fieldId: "_2", value: "3" }, { blockId: "third-block", sectionId: "other-section", fieldId: "_1", value: "3" }],
keys = ['blockId', 'sectionId', 'fieldId'],
result = data.reduce((r, o) => {
keys.reduce(
(q, k, i, { length }) => q[o[k]] ??= i + 1 === length ? o.value : {},
r
);
return r;
}, {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Approach by taking all values of the object and assign the last item as value for the most nested object.
This approach relies on the order of the values in each object.
const
data = [{ blockId: "first-block", sectionId: "first-section", fieldId: "_1", value: "0" }, { blockId: "first-block", sectionId: "first-section", fieldId: "_2", value: "1" }, { blockId: "first-block", sectionId: "second-section", fieldId: "_1", value: "1" }, { blockId: "second-block", sectionId: "first-section", fieldId: "_1", value: "1" }, { blockId: "second-block", sectionId: "some-section", fieldId: "_2", value: "3" }, { blockId: "third-block", sectionId: "other-section", fieldId: "_1", value: "3" }],
result = data.reduce((r, o) => {
const
values = Object.values(o),
value = values.pop();
values.reduce(
(q, k, i, { length }) => q[k] ??= i + 1 === length ? value : {},
r
);
return r;
}, {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You also need to copy the properties (fields) of the innermost (section) object:
const shapeComplex = (acc, item) => {
console.log('acc:', JSON.stringify(acc));
acc[item.blockId] = {
...acc[item.blockId],
[item.sectionId]: {
...acc[item.blockId]?.[item.sectionId],
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[item.fieldId]: item.value
}
};
return acc
}
I would however recommend to either always use object spread on every level
const shapeComplex = (acc, item) => {
return {
...acc,
[item.blockId]: {
...acc[item.blockId],
[item.sectionId]: {
...acc[item.blockId]?.[item.sectionId],
[item.fieldId]: item.value
}
}
};
}
or to use mutations:
const shapeComplex = (acc, {blockId, sectionId, fieldId, value}) => {
const block = acc[blockId] ?? (acc[blockId] = {});
const section = block[sectionId] ?? (block[sectionId] = {});
section[fieldId] = value;
return acc;
}
As #Nina showed in here answer, you can generalise this to arbitrarily deep assignments.
You can do the following,
const flatArray = [
{ "blockId": "first-block", "sectionId": "first-section", "fieldId": "_1", "value": "0" },
{ "blockId": "first-block", "sectionId": "first-section", "fieldId": "_2", "value": "1" },
{ "blockId": "first-block", "sectionId": "second-section", "fieldId": "_1", "value": "1" },
{ "blockId": "second-block", "sectionId": "first-section", "fieldId": "_1", "value": "1" },
{ "blockId": "second-block", "sectionId": "some-section", "fieldId": "_2", "value": "3" },
{ "blockId": "third-block", "sectionId": "other-section", "fieldId": "_1", "value": "3" }];
const shapeComplex = (acc, item) => {
if(acc[item.blockId]) {
acc[item.blockId] = { ...acc[item.blockId], [item.sectionId]: {...acc[item.blockId][item.sectionId], [item.fieldId]: item.value } }
} else {
acc[item.blockId] = { ...acc[item.blockId], [item.sectionId]: {[item.fieldId]: item.value } }
}
return acc
}
const transformComplex = (arr) => {
return arr.reduce((acc, item) => shapeComplex(acc, item), {});
}
console.log(transformComplex(flatArray));
You are making a tree from a flat data structure. Specify the tree hierarchy (levels) and
properties to use to create a leaf node data element.
Example:
function treeFrom (arr, levels, name, value) {
return arr.reduce(
(root,item) =>
{
var node = root;
for (let level of levels) /* descend to bottom tier */
{
levelvalue = item[level];
if (! node[levelvalue]) node[levelvalue] = {};
node = node[levelvalue];
}
node[item[name]] = item[value];
return root;
}
,
{}
)
}
console.log ( treeFrom(flatArray, ['blockId', 'sectionId'], 'fieldId', 'value') );

Map an array as per true or false set in another array

I have an array of item "mockData" & a Filter array "filter" in angular 8:
filter=[
{column:"name",show:true},
{column:"Sex",show:false},
];
mockData=[
{name:"test",sex:"m"},
{name:"test2",sex:"m"},
{name:"test3",sex:"f"},
{name:"test4",sex:"f"},
];
I want to map only the columns of mockData which are set as true in filter array.
result should look something like this.
[
{name:"test"},
{name:"test2"},
{name:"test3"},
{name:"test4"},
]
it should check in filter mandatorily.
const filter = [
{
column: "name",
show: true
},
{
column: "sex",
show: false
}
];
const mockData = [
{
name: "test",
sex: "m"
},
{
name: "test2",
sex: "m"
},
{
name: "test3",
sex: "f"
},
{
name: "test4",
sex: "f"
}
];
const filteredMockData = mockData.map(data =>
Object.entries(data).reduce(
(result, [key, value]) =>
filter.find(f => f.column === key && f.show)
? { ...result, [key]: value }
: result,
{}
)
);
console.log(filteredMockData);

How to create an array based on two array

I have an array of object, this array contains differents names.
[ "Foo", "Bar", "Test", "Other" ];
And another array of object
[ { name:"Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 } ]
I need to create an array of them, the new array contains sub array with a size of 2, first index the name and second index the value.
The order of the array need to be the same of the first one (array of names).
Like
[ ["Foo", 120], ["Bar", 159], ["Test", undefined], ["Other", 1230] ]
So I try this code, but my output is not correct. The order of name is correct but the order of value is not.
var order = ["Foo", "Bar", "Test", "Other"];
var values = [{ name: "Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 }];
var array = order.map(function(name, i) {
return [name, (values[i] && values[i].value) ];
})
console.log(array)
You could take a Map and get the items in the wanted order.
var names = [ "Foo", "Bar", "Test", "Other" ],
objects = [{ name: "Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 }],
map = new Map(objects.map(({ name, value }) => [name, value])),
result = names.map(name => [name, map.get(name)])
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You're nearly there - you just need to find the correct value:
var order = ["Foo", "Bar", "Test", "Other"];
var values = [{ name: "Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 }];
var array = order.map(function(name, i) {
return [name, values.some(e => e.name == name) ? values.find(e => e.name == name).value : undefined];
})
console.log(array)
ES5 syntax:
var order = ["Foo", "Bar", "Test", "Other"];
var values = [{ name: "Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 }];
var array = order.map(function(name, i) {
return [name, values.some(function(e) {
return e.name == name;
}) ? values.find(function(e) {
return e.name == name;
}).value : undefined];
});
console.log(array)
Check out my solution. Hope this helps.
const a = [ "Foo", "Bar", "Test", "Other" ];
const b = [ { name:"Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 } ];
const res = a.map((item) => [ item, (b.find(({ name }) => name === item) || {}).value ])
console.log(res)
You need to use entries in "order" to lookup "name" in values
var order = ["Foo", "Bar", "Test", "Other"];
var values = [{ name: "Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 }];
var array = order.map(function(key, i) {
let found = values.find(({name}) => name === key);
return [key, found && found.value ];
})
console.log(array)
You could use map and take the Object.values of the found item, or a default one
const arr1 = [ "Foo", "Bar", "Test", "Other" ];
const arr2 = [ { name:"Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 } ];
const res = arr1.map(e => Object.values(arr2.find(({name}) => name === e) || ({name: e, value: undefined})));
console.log(res);
var order = ["Foo", "Bar", "Test", "Other"];
var values = [{ name: "Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 }];
var result = [];
orders.forEach((f) => {
let found = false;
values.forEach(s => {
if (f === s.name) {
result.push([f, s.value]);
found = true;
}
});
if (!found) {
result.push([f, undefined]);
}
});

Categories