Adding position/order in array of objects - javascript

I have an array of objects like below:
[{
"id": 1,
"Size": 90,
"Maturity": 24,
},
{
"id": 2,
"Size": 85,
"Maturity": 22,
},
{
"id": 3,
"Size": 80,
"Maturity": 20,
}]
I need to this Array on basis of different property value sorting (eg: Maturity) and also add a column order which has the ascending order/rank.
Eg:
[{
"id": 1,
"Size": 90,
"Maturity": 22,
"Order": 2
},
{
"id": 2,
"Size": 85,
"Maturity": 25,
"Order": 3
},
{
"id": 3,
"Size": 80,
"Maturity": 20,
"Order": 1
}]

const arr = [{
"id": 1,
"Size": 90,
"Maturity": 24,
},
{
"id": 2,
"Size": 85,
"Maturity": 22,
},
{
"id": 3,
"Size": 80,
"Maturity": 20,
}];
arr
.map((item,index) => ({ ...item, Order: index + 1 }))
.sort((a, b) => b.Maturity - a.Maturity)

Sort the array with sort and then add prop to each object with respect to the index they are sorted on with forEach:
var inp = [{
id: 1,
Size: 90,
Maturity: 24,
},
{
id: 2,
Size: 85,
Maturity: 22,
},
{
id: 3,
Size: 80,
Maturity: 20,
}]
// Sort
inp.sort(function(a, b){
return a.Maturity == b.Maturity ? 0 : +(a.Maturity > b.Maturity) || -1;
});
// add prop
inp.forEach(function(row, index) {
row.index = index + 1;
});
console.log(inp)

var objs = [
{
"id": 1,
"Size": 90,
"Maturity": 24,
},
{
"id": 2,
"Size": 85,
"Maturity": 22,
},
{
"id": 3,
"Size": 80,
"Maturity": 20,
}];
function compare(a,b) {
if (a.Size < b.Size)
return -1;
if (a.Size > b.Size)
return 1;
return 0;
}
objs.sort(compare);
for (var i = 0; i < objs.length; i++) {
objs[i].Order = i+1;
}
console.log(objs);

Related

Sorting index of array based on another array of Object in javascript/Vue

i have 2 array of objects and I need to sort one array of object depends on another array key value
array1: [
{
group: 'GROUP1',
sort_order: 1,
},
{
group: 'GROUP2',
sort_order: 2,
},
{
group: 'GROUP3',
sort_order: 3,
}
],
array2: {
'GROUP3' : [
{
"price": 10,
"amount": 2,
},
{
"price": 45,
"amount": 7,
},
],
'GROUP2' : [
{
"price": 10,
"amount": 2,
},
{
"price": 45,
"amount": 7,
},
],
'GROUP1' : [
{
"price": 10,
"amount": 2,
},
{
"price": 45,
"amount": 7,
},
]
}
No I need to order my array2 indexes based on array1 "sort_order".
i am expecting the order of array2 something like GROUP1, GROUP2, GROUP3
Thanks in advance
let sorted = Object.entries(array2).sort(([groupA], [groupB]) =>
array1.find(e => e.group === groupA).sort_order -
array1.find(e => e.group === groupB).sort_order)
would give you
[
[
"GROUP1",
[
{
"price": 10,
"amount": 2
},
{
"price": 45,
"amount": 7
}
]
],
[
"GROUP2",
[
{
"price": 10,
"amount": 2
},
{
"price": 45,
"amount": 7
}
]
],
...
As i understood you need to sort second array using info from first one. I prefer to keep original array and do sort in computed property.
Example:
const app = new Vue({
el:'#app',
data: () => ({
array1: [
{
group: 'GROUP1',
sort_order: 1,
},
{
group: 'GROUP2',
sort_order: 2,
},
{
group: 'GROUP3',
sort_order: 3,
},
],
array2: {
'GROUP3' : [
{
"price": 10,
"amount": 2,
},
{
"price": 45,
"amount": 7,
},
],
'GROUP2' : [
{
"price": 10,
"amount": 2,
},
{
"price": 45,
"amount": 7,
},
],
'GROUP1' : [
{
"price": 10,
"amount": 2,
},
{
"price": 45,
"amount": 7,
},
],
},
}),
mounted() {
setTimeout(() => {
console.log(this.sortedArray2);
}, 1000);
},
computed: {
sortedArray2() {
const arr2 = { ...this.array2 };
this.array1.map(item1 => {
arr2[item1.group] = arr2[item1.group].sort((a, b) => {
switch(item1.sort_order) {
case 1: {
return a.price > b.price ? 1 : -1;
}
case 2: {
return a.price < b.price ? 1 : -1;
}
default: {
return a.amount < b.amount ? 1 : -1;
}
}
});
});
return arr2;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
</div>

How to push a set of arrays into main array?

I want to push some arrays into the main array in single function. Here is the example :
let MainArr = [
{
"date": "2021-02-24T18:30:00.000Z",
"age": "9",
"id": 74,
"time": 4.00 },
{"date": "2021-02-24T18:30:00.000Z",
"age":"9",
"id": 74,
"time": 4.00
}];
I am getting all this data from API so next array will be like this:
let arr1 = [{
"id": 1,
"arrKey1": "schedule1"
}, {
"id": 2,
"arrKey1": "schedule2"
}]
let arr2 = [{
"id": 1,
"arrKey2": "bus1"
}, {
"id": 2,
"arrKey2": "bus2"
}]
let arr3 = [{
"id": 1,
"arrKey3": "car1"
}, {
"id": 2,
"arrKey3": "1"
}]
Now the result should reflect like this:
[{
"date": "2021-02-24T18:30:00.000Z",
"age": "9",
"id": 74,
"time": 4.00,
"arrKey1":"schedule1",
"arrKey2 ":"bus1",
"arrKey3":"car1"},
{"date ": "2021-02-24T18:30:00.000Z",
"age": "9",
"id": 74,
"time": 4.00,
"arrKey1": "schedule2",
"arrKey2": "bus2",
"arrKey3": "1"
}];
In ES6 you can use three dots. see the example:
let MainArr = [1, 2, 3];
let arr1 = [4, 5, 6];
console.log('before: ', MainArr)
MainArr.push(...arr1)
console.log('after pushing arr1: ', MainArr)

Merge elements in array of objects based on property

I have an array of objects. Each object has an amount and value property. If an object has the same amount value I would like to add that value to that object.
Here's an example array:
const array = [
{
"key": 1,
"amount": 11,
"value": "were"
},
{
"key": 2,
"amount": 6,
"value": "locomotives"
},
{
"key": 3,
"amount": 5,
"value": "They"
},
{
"key": 4,
"amount": 5,
"value": "with"
},
{
"key": 5,
"amount": 4,
"value": "used"
}
]
I would like to transform this to resemble this:
const array = [
{
"key": 1,
"amount": 11,
"value": "were"
},
{
"key": 2,
"amount": 6,
"value": "locomotives"
},
{
"key": 3,
"amount": 5,
"value": "They, width"
},
{
"key": 5,
"amount": 4,
"value": "used"
}
]
I've tried reduce and map but I can't seem to get it to join,
I think should work with .reduce():
const array = [
{
"key": 1,
"amount": 11,
"value": "were"
},
{
"key": 2,
"amount": 6,
"value": "locomotives"
},
{
"key": 3,
"amount": 5,
"value": "They"
},
{
"key": 4,
"amount": 5,
"value": "with"
},
{
"key": 5,
"amount": 4,
"value": "used"
}
];
const result = array.reduce((a, c) => {
const found = a.find(e => e.amount === c.amount);
if (found) found.value = `${found.value}, ${c.value}`;
return found ? a : a.concat(c);
}, []);
console.log(result);
I hope that helps!
You can use .reduce() with an ES6 Map by indexing by the amount value. If an object's amount value already exists within the map, you can update its value to include the current objects value. If the amount value isn't in the map, you can set it as a key and the current object as the value. Lastly, you can use Array.from() to get an array of object values from the iterator returned by .values()
const array = [ { "key": 1, "amount": 11, "value": "were" }, { "key": 2, "amount": 6, "value": "locomotives" }, { "key": 3, "amount": 5, "value": "They" }, { "key": 4, "amount": 5, "value": "with" }, { "key": 5, "amount": 4, "value": "used" } ];
const res = Array.from(array.reduce((m, o) => {
const curr = m.get(o.amount);
return m.set(o.amount, curr && {...curr, value: `${curr.value}, ${o.value}`} || o);
}, new Map).values());
console.log(res);
mine..
const array1 =
[ { key: 1, amount: 11, value: "were" }
, { key: 2, amount: 6, value: "locomotives" }
, { key: 3, amount: 5, value: "They" }
, { key: 4, amount: 5, value: "with" }
, { key: 5, amount: 4, value: "used" }
]
const array2 = array1.reduce((a,c)=>
{
let same = a.find(e=>e.amount===c.amount)
if (same) same.value += ', '+c.value
else a.push(c)
return a
},[])
console.log( array2 )
In each iteration of reduce method, we can add value if there is an already added value:
const result = array.reduce((a, c) => {
a[c.amount] = a[c.amount] || c;
if ((Object.keys(a).includes(c.amount.toString())) && (a[c.amount].value!= c.value))
a[c.amount].value += ', ' + c.value;
return a;
}, {});
An example:
const array = [
{
"key": 1,
"amount": 11,
"value": "were"
},
{
"key": 2,
"amount": 6,
"value": "locomotives"
},
{
"key": 3,
"amount": 5,
"value": "They"
},
{
"key": 4,
"amount": 5,
"value": "with"
},
{
"key": 5,
"amount": 4,
"value": "used"
}
];
const result = array.reduce((a, c) => {
a[c.amount] = a[c.amount] || c;
if ((Object.keys(a).includes(c.amount.toString())) && (a[c.amount].value!= c.value))
a[c.amount].value += ', ' + c.value;
return a;
}, {});
console.log(result);
Use forEach loop and build an object. If the amount key already exist then append the value string.
const update = data => {
const res = {};
data.forEach(item => {
res[item.amount] =
item.amount in res
? {
...res[item.amount],
value: `${res[item.amount].value}, ${item.value}`
}
: { ...item };
});
return Object.values(res);
};
const array = [
{
key: 1,
amount: 11,
value: "were"
},
{
key: 2,
amount: 6,
value: "locomotives"
},
{
key: 3,
amount: 5,
value: "They"
},
{
key: 4,
amount: 5,
value: "with"
},
{
key: 5,
amount: 4,
value: "used"
}
];
console.log(update(array));

match 2 properties' values in array of objects and filter matches based on a 3rd property's value

I've got a graph with nodes that can be connected to multiple other nodes.
Every node represents an object in an array. Within every node's object is an array that contains the ids of all the nodes linked to this node and its depth:
nodes: [
{"id":1, "depth":0, "next":[], "children":[2, 3]}, // nodes.next = [2, 3]
{"id":2, "depth":1, "next":[], "children":[1, 4, 5]}, // nodes.next = [4, 5]
{"id":3, "depth":1, "next":[], "children":[1, 6, 7]}, // nodes.next = [6, 7]
{"id":4, "depth":2, "next":[], "children":[2, 8]}, // nodes.next = [8]
{"id":5, "depth":2, "next":[], "children":[2, 9]} // nodes.next = [9]
]
I would like to traverse the graph from a certain node.
The problem is that a node's children array contains all the nodes linked to it. A node with a depth of 2 points back to a node with a depth of 1.
So I would like to create a new array within the nodes' objects, let's say nodes.next and get rid of the children that point back to a node that has a depth lower than itself.
The part that really baffles me is checking the depth of the nodes in nodes.children. I even haven't been near the part where I might check if the depth of a node in nodes.children is higher than nodes[i].depth and push nodes[i].children[i] to nodes[i].next.
If there is better way to solve this problem I'd be happy to know. My attemps have been fruitless in many ways alike:
let childDepth;
for (let i = 0; i < nodes.length; i++) {
for (let child in nodes[i].children) {
if (nodes.id === child) {
childDepth = nodes[i].depth;
}
if (childDepth > graph.nodes[i].depth) {
nodes[i].next.push(child)
}
}
}
Updated array:
const nodes = [
{ "id": 37, "depth": 0, "children": [210, 395, 265], "next": [] },
{ "id": 210, "depth": 1, "children": [37, 260, 259, 391],"next": [] },
{ "id": 256, "depth": 2, "children": [265], "next": [] },
{ "id": 259, "depth": 2, "children": [210, 397, 396], "next": [] },
{ "id": 260, "depth": 2, "children": [210], "next": [] },
{ "id": 265, "depth": 1, "children": [37, 256, 388, 394, 271, 269], "next": [] },
{ "id": 269, "depth": 2, "children": [265], "next": [] },
{ "id": 271, "depth": 2, "children": [265], "next": [] },
{ "id": 388, "depth": 2, "children": [265], "next": [] },
{ "id": 391, "depth": 2, "children": [210], "next": [] },
{ "id": 394, "depth": 2, "children": [265], "next": [] },
{ "id": 395, "depth": 1, "children": [37], "next": [] },
{ "id": 396, "depth": 3, "children": [259, 413], "next": [] },
{ "id": 397, "depth": 3, "children": [259], "next": [] },
{ "id": 413, "depth": 4, "children": [396], "next": [] }
];
Kindly take a look on the below code to see if it's what you're looking for
const array = [
{id:1, depth:0, next:[], children:[2, 3]},
{id:2, depth:1, next:[], children:[1, 4, 5]},
{id:3, depth:1, next:[], children:[1, 6, 7]},
{id:4, depth:2, next:[], children:[2, 8]},
{id:5, depth:2, next:[], children:[2, 9]}
]
array.forEach(x => {
let { children, depth } = x;
for(let i=depth; i< children.length; i++){
x.next.push(children[i]);
}
});
Output as below:
[
{"id":1,"depth":0,"next":[2,3],"children":[2,3]},
{"id":2,"depth":1,"next":[4,5],"children":[1,4,5]},
{"id":3,"depth":1,"next":[6,7],"children":[1,6,7]},
{"id":4,"depth":2,"next":[],"children":[2,8]},
{"id":5,"depth":2,"next":[],"children":[2,9]}
]

ES6: Find an object in an array by one of its properties

I'm trying to figure out how to do this in ES6...
I have this array of objects..
const originalData=[
{"investor": "Sue", "value": 5, "investment": "stocks"},
{"investor": "Rob", "value": 15, "investment": "options"},
{"investor": "Sue", "value": 25, "investment": "savings"},
{"investor": "Rob", "value": 15, "investment": "savings"},
{"investor": "Sue", "value": 2, "investment": "stocks"},
{"investor": "Liz", "value": 85, "investment": "options"},
{"investor": "Liz", "value": 16, "investment": "options"}
];
..and this new array of objects where I want to add each person's total value of their investment types (stocks, options, savings)..
const newData = [
{"investor":"Sue", "stocks": 0, "options": 0, "savings": 0},
{"investor":"Rob", "stocks": 0, "options": 0, "savings": 0},
{"investor":"Liz", "stocks": 0, "options": 0, "savings": 0}
];
I loop through originalData and save each property of the "current object" in a let..
for (let obj of originalData) {
let currinvestor = obj.investor;
let currinvestment = obj.investment;
let currvalue = obj.value;
..but here I want to find the obect in newData that has the property = currinvestor (for the "investor" key)
...then add that investment type's (currinvestment) value (currvalue)
}
newData.find(x => x.investor === investor)
And the whole code:
const originalData = [
{ "investor": "Sue", "value": 5, "investment": "stocks" },
{ "investor": "Rob", "value": 15, "investment": "options" },
{ "investor": "Sue", "value": 25, "investment": "savings" },
{ "investor": "Rob", "value": 15, "investment": "savings" },
{ "investor": "Sue", "value": 2, "investment": "stocks" },
{ "investor": "Liz", "value": 85, "investment": "options" },
{ "investor": "Liz", "value": 16, "investment": "options" },
];
const newData = [
{ "investor": "Sue", "stocks": 0, "options": 0, "savings": 0 },
{ "investor": "Rob", "stocks": 0, "options": 0, "savings": 0 },
{ "investor": "Liz", "stocks": 0, "options": 0, "savings": 0 },
];
for (let {investor, value, investment} of originalData) {
newData.find(x => x.investor === investor)[investment] += value;
}
console.log(newData);
.as-console-wrapper.as-console-wrapper { max-height: 100vh }
I would use some derivative of this:
var arrayFindObjectByProp = (arr, prop, val) => {
return arr.find( obj => obj[prop] == val );
};

Categories