I have an array of and array of objects similar to this :
const oldArray =[
[{'val': 12, 'rank':1},{'val': 122, 'rank':1},{'val': 112, 'rank':1}],
[{'val': 12, 'rank':2},{'val': 122, 'rank':2},{'val': 112, 'rank':2}],
[{'val': 12, 'rank':3},{'val': 122, 'rank':3},{'val': 112, 'rank':3}]
]
how can I retrieve the array that has the 'rank' values set to 3?
const newArray = [{'val': 12, 'rank':3},{'val': 122, 'rank':3},{'val': 112, 'rank':3}];
thanks in advance!
You could use Array.prototype.flat() with Array.prototype.filter() method to get the result.
const oldArray = [
[
{ val: 12, rank: 1 },
{ val: 122, rank: 1 },
{ val: 112, rank: 1 },
],
[
{ val: 12, rank: 2 },
{ val: 122, rank: 2 },
{ val: 112, rank: 2 },
],
[
{ val: 12, rank: 3 },
{ val: 122, rank: 3 },
{ val: 112, rank: 3 },
],
];
const ret = oldArray.flat().filter((x) => x.rank === 3);
console.log(ret);
Assuming all ranks within the inner arrays are the same you could use find() and check the rank of the first element within each array.
const oldArray = [
[{'val': 12, 'rank':1},{'val': 122, 'rank':1},{'val': 112, 'rank':1}],
[{'val': 12, 'rank':2},{'val': 122, 'rank':2},{'val': 112, 'rank':2}],
[{'val': 12, 'rank':3},{'val': 122, 'rank':3},{'val': 112, 'rank':3}],
];
const newArray = oldArray.find(([element]) => element.rank == 3);
console.log(newArray);
This answer uses destructuring to extract the first element of each inner array.
This answer will also throw an error if the inner array can be empty (accessing "rank" of undefined), which can be avoided by using optional chaining. eg. element?.rank == 3
Related
I have an List and I am trying to find if there is any "DishId" with value 63 and if found , i wanted to return the object count of the element, for example here I wanted to return 1 as it is the first object in the list.
Below is the list :
result = [ TextRow {
BagId: 'BTWDCZ46826',
BagStatus: 1,
DishId: 63,
SellerId: 205,
Qty: 1,
PreperationTime: 240
} ,
{
BagId: 'BTWDCZ46234',
BagStatus: 1,
DishId: 69,
SellerId: 195,
Qty: 1,
PreperationTime: 150
}
]
Below is the code that I tried to find if DishId with 63 is found or not
if(results.find(({ DishId }) => dishId === req.body.dishId)){
index = results.indexOf(({ DishId }) => x.dishId === req.body.dishId).DishId;
console.log("Found");
console.log("Index is ", index);
}
You need the Index not the object found itself, So use findIndex instead of find:
const arr = [{
BagId: 'BTWDCZ46826',
BagStatus: 1,
DishId: 63,
SellerId: 205,
Qty: 1,
PreperationTime: 240
},
{
BagId: 'BTWDCZ46234',
BagStatus: 1,
DishId: 69,
SellerId: 195,
Qty: 1,
PreperationTime: 150
}
]
console.log(arr.findIndex(({
DishId
}) => DishId === 63))
I wanted to return 1 as it is the first object
It gonna return 0 not 1, since array in JS are zero based
const result = [{
BagId: 'BTWDCZ46826',
BagStatus: 1,
DishId: 63,
SellerId: 205,
Qty: 1,
PreperationTime: 240
} ,
{
BagId: 'BTWDCZ46234',
BagStatus: 1,
DishId: 69,
SellerId: 195,
Qty: 1,
PreperationTime: 150
}
];
const idx = result.findIndex(el => el.DishId === 69);
console.log(idx);
Also, there was an error in your result array.
Btw, findIndex returns -1 if searched element is not present. See findIndex MDN Page
I am trying to make a javaScript game of housie/bingo game. I used the library npm tambola-generator which returns auto generated tickets.
The server side process generates an array similar to this one ...
[{
"_entries": [[0,17,0,0,41,53,0,78,86], [4,0,0,35,0,58,67,80,0]/*, [ ... ] */],
}, {
"_entries": [[0,16,23,0,41,51,0,0,88], [2,20,0,31,43,56,0,0,0]/*, [ ... ] */],
}, {
"_entries": [[0,0,23,33,0,51,0,73,87], [1,0,0,35,42,58,68,0,0]/*, [ ... ] */],
}, {
// ... more items like that ...
}]
I want each ticket to feature a serial number which should be equal to a ticket items's array index but starting with the base of 1 instead of 0.
How does one include such a ticket number so that I can manage tickets for players?
I am just a beginner I couldn't solve it out. The target structure of the above example code should look like the following one ...
[{
"ticketNum": 1,
"_entries": [[0,17,0,0,41,53,0,78,86], [4,0,0,35,0,58,67,80,0]/*, [ ... ] */],
}, {
"ticketNum": 2,
"_entries": [[0,16,23,0,41,51,0,0,88], [2,20,0,31,43,56,0,0,0]/*, [ ... ] */],
}, {
"ticketNum": 3,
"_entries": [[0,0,23,33,0,51,0,73,87], [1,0,0,35,42,58,68,0,0]/*, [ ... ] */],
}, {
// ... more items like that ...
}]
Just use Array.prototype.map for achieving this task.
const entries = [{
"_entries": [
[0, 17, 0, 0, 41, 53, 0, 78, 86],
[4, 0, 0, 35, 0, 58, 67, 80, 0]
],
}, {
"_entries": [
[0, 16, 23, 0, 41, 51, 0, 0, 88],
[2, 20, 0, 31, 43, 56, 0, 0, 0]
],
}, {
"_entries": [
[0, 0, 23, 33, 0, 51, 0, 73, 87],
[1, 0, 0, 35, 42, 58, 68, 0, 0]
],
}];
const tcktEntries = entries.map((entry, index) => {
return {
ticketNum: index + 1,
...entry
};
});
console.log({
tcktEntries
});
.as-console-wrapper {
min-height: 100%!important;
top: 0;
}
I have this array:
course_ids: [11, 70, 3]
And this array of objects:
arr: [{
course_id: 11,
course_hour_id: 56,
name: 'John',
},
{
course_id: 70,
course_hour_id: 72,
name: 'Lily',
},{
course_id: 3,
course_hour_id: 12,
name: 'Mike',
}]
Given these two, I want to make an array of course_hour_ids: [56, 72, 12]
How can I do that using React.js?
At first filter then map
let objArray = [
{
course_id: 11,
course_hour_id: 56,
name: 'John',
},
{
course_id: 70,
course_hour_id: 72,
name: 'Lily',
},
{
course_id: 3,
course_hour_id: 12,
name: 'Mike',
}
];
let course_ids = [11, 70, 3];
let result = objArray.filter(array => course_ids.some(filter => filter == array.course_id)).map(a => a.course_hour_id);
console.log(result);
You colud filter initial array and then map the result array on course_hour_id like:
let arr = [
{
course_id: 11,
course_hour_id: 56,
name: 'John',
},
{
course_id: 70,
course_hour_id: 72,
name: 'Lily',
},{
course_id: 3,
course_hour_id: 12,
name: 'Mike',
}
]
let course_ids = [11, 70, 3];
let res = arr.filter(el => {
return course_ids.includes(el.course_id);
})
console.log(res.map(el => el.course_hour_id))
const course_ids = [11, 70, 3];
const arr = [{
course_id: 11,
course_hour_id: 56,
name: 'John',
},
{
course_id: 70,
course_hour_id: 72,
name: 'Lily',
}, {
course_id: 3,
course_hour_id: 12,
name: 'Mike',
}
];
const result = arr.map(x => {
if (course_ids.includes(x.course_id))
return x.course_hour_id
});
console.log(result)
No need to use .filter
course_ids
.map(course_id =>
arr.find(arrItem =>
arrItem.course_id === course_id)
?.course_hour_id);
The above solutions uses optional chaining. If you don't use that you can write:
course_ids
.map(course_id =>
arr.some(arrItem =>
arrItem.course_id === course_id)
? arr.find(arrItem =>
arrItem.course_id === course_id).course_hour_id
: null
);
I have an array that contains nested arrays.
The nested array can contain multiple objects.
const axisChoiceLoop = _.map(groupByAxisChoice)
output:
[
0: [ {age: 15, count: 242, role: "JW"}] // length 1
1: [ {age: 21, count: 995, role: "JW"} , {age: 21, count: 137, role: "SW"} ] // length 2
2: [ {age: 25, count: 924, role: "JW"}, {age: 25, count: 455, role: "SW"}, {age: 25, count: 32, role: "EW"} ]
]
I would like the nested arrays to be single objects, using their role as the key, and count as the value
expected output would look like this
[
{age :15, JW: 242},
{age: 21, JW:995, SW: 137},
{age: 25, JW: 924, SW: 445, EW: 32}
]
Edit: I have tried the following code
const result = groupByAxisChoice.reduce(
(obj, item) => Object.assign(obj, { [item.role]: item.count }),
{},
)
Which outputs: { undefined: undefined }
Figured it out...
const result = groupByAxisChoice.map(items =>
items.reduce((obj, item) => Object.assign(obj, { age: item.age, [item.role]: item.count }), {}),
)
This is what I ended up with, I know it's not optimized:
var arr = [
[ {age: 15, count: 242, role: "JW"}], // length 1
[ {age: 21, count: 995, role: "JW"} , {age: 21, count: 137, role: "SW"} ], // length 2
[ {age: 25, count: 924, role: "JW"}, {age: 25, count: 455, role: "SW"}, {age: 25, count: 32, role: "EW"} ]
];
var newArr = [];
arr.forEach(function(a) {
var ob = {age: a[0].age};
a.forEach(d => ob[d.role] = d.count);
newArr.push(ob);
});
I'll try to make it better (i don't know how to use underscore.js)...
another solutions
const b = a.map(item => {
return item.reduce((arr,curr) => {
return {
...arr,
['age']: curr['age'],
[curr['role']]: curr['count'],
}
}, {})
})
console.log(b)
I've been trying to merge data and get this result:
data = [{serviceID: 22, quantite: 120, typeConviveId: 6},
{serviceID: 23, quantite: 240, typeConviveId: 6},
{serviceID: 24, quantite: 100, typeConviveId: 7},
{serviceID: 25, quantite: 150, typeConviveId: 7}]
what needed at end :
result: [ { "22": "120", "23": "240", "typeConviveId": "6"},
{ "24": "100", "25": "150", "typeConviveId": "7" } ]
You can use a combination of Array.prototype.map, Array.prototype.filter and Array.prototype.reduce, along with a list of unique typeConviveId deduped using a Set with [...new Set(data.map(x=>x.typeConviveId))]:
const data = [{serviceID: 22, quantite: 120, typeConviveId: 6}, {serviceID: 23, quantite: 240, typeConviveId: 6}, {serviceID: 24, quantite: 100, typeConviveId: 7}, {serviceID: 25, quantite: 150, typeConviveId: 7}];
const result = [...new Set(data.map(x => x.typeConviveId))].map(
id => data
.filter(x => x.typeConviveId === id)
.reduce((acc, val) => {
return { ...acc,
[val.serviceID]: '' + val.quantite
}
}, {
typeConviveId: '' + id
})
);
console.log(result);
You can use array reduce & in the callback function use findIndex to get the object which has same typeConviveId. findIndex will return the index of the object which has same findIndex from the accumulator array which is represented by acc. In fiindIndex is -1 then create a new object with required keys and push it in the accumulator array. If there already exist an array with same typeConviveId then just update the object with new key
let data = [{
serviceID: 22,
quantite: 120,
typeConviveId: 6
},
{
serviceID: 23,
quantite: 240,
typeConviveId: 6
},
{
serviceID: 24,
quantite: 100,
typeConviveId: 7
},
{
serviceID: 25,
quantite: 150,
typeConviveId: 7
},
{
serviceID: 25,
quantite: 250,
typeConviveId: 7
}
]
let newData = data.reduce(function(acc, curr) {
let findIndex = acc.findIndex(function(item) {
return item.typeConviveId === curr.typeConviveId;
})
if (findIndex === -1) {
acc.push({
typeConviveId: curr.typeConviveId,
[curr.serviceID]: curr.quantite
})
} else {
acc[findIndex][curr.serviceID] = curr.quantite
}
return acc;
}, []);
console.log(newData)
The expected result have a problem. If there is a duplicate key for example suppose if the key like 22 i s repeated , then it will have the last value.
{
serviceID: 25,
quantite: 150,
typeConviveId: 7
},
{
serviceID: 25,
quantite: 250,
typeConviveId: 7
}
In this case serviceID in both object is 25, So its value will be 250. It will not have two keys with separate value