Find index of element in a List - javascript

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

Related

Rename (add suffix to) every key except 2 in every object in array of objects javascript

We have the following javascript array:
[
{ team: 1, stat1: 17, stat2: 25, var1: 'okay', var3: 'nah', here: 24 },
{ team: 1, stat1: 17, stat2: 25, var1: 'okay', var3: 'nah', here: 24 },
{ team: 1, stat1: 17, stat2: 25, var1: 'okay', var3: 'nah', here: 24 }
]
and we are looking to add the suffix Agst to every key other than the team key, such that our output is:
[
{ team: 1, stat1Agst: 17, stat2Agst: 25, var1Agst: 'okay', var3Agst: 'nah', hereAgst: 24 },
{ team: 1, stat1Agst: 17, stat2Agst: 25, var1Agst: 'okay', var3Agst: 'nah', hereAgst: 24 },
{ team: 1, stat1Agst: 17, stat2Agst: 25, var1Agst: 'okay', var3Agst: 'nah', hereAgst: 24 }
]
Each object in our actual array of objects has >100 keys, and for this reason we are looking for a solution that specifically changes all key names other than team, rather than changing all keys with names ['stat1', 'stat2', 'var1', 'var3', 'here'] if possible.
You can easily achieve the result using map and Object.entries as:
const arr = [
{ team: 1, stat1: 17, stat2: 25, var1: "okay", var3: "nah", here: 24 },
{ team: 1, stat1: 17, stat2: 25, var1: "okay", var3: "nah", here: 24 },
{ team: 1, stat1: 17, stat2: 25, var1: "okay", var3: "nah", here: 24 },
];
const result = arr.map((o) =>
Object.fromEntries(
Object.keys(o).map((key) =>
key === "team" ? [key, o[key]] : [`${key}Agst`, o[key]]
)
)
);
console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
This seems to be working okay for me.
arr = [
{ team: 1, stat1: 17, stat2: 25, var1: 'okay', var3: 'nah', here: 24 },
{ team: 1, stat1: 17, stat2: 25, var1: 'okay', var3: 'nah', here: 24 },
{ team: 1, stat1: 17, stat2: 25, var1: 'okay', var3: 'nah', here: 24 }
]
arr.forEach((row, index, theArray) => {
let rowKeys = Object.keys(row).filter(key => key !== 'team');
rowKeys.forEach(key => {
theArray[index][`${key}Agst`] = theArray[index][key];
delete theArray[index][key];
});
});
console.log(arr);

How to insert serial numbers for every object in JavaScript

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;
}

finding object in an array

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

convert nested array to single object with key values Javascirpt

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)

How can I get objects from array with specific id compares from another array numbers

I need to compare id objects array from a firstArray and array numbers (secondArray) and return a new array with objects from the first array which id number exists in the second array.
So at the end, I want a new array with objects with id 39 and 41.
Actually I find something like this:
const result = arr2.filter(o => arr1.find(x => x.id === o));
const arr1 =
"blocks": [
{
"id": 1,
"functions": [ 0, 1 ]
},
{
"id": 39,
"functions": [ 0, 1, 3, 4 ]
},
{
"id": 41,
"functions": [ 0, 1 ]
}
]
const arr2 = [39, 41]
You can use includes() function during filtering. Includes() works like in array function.
const arr1 =
[ {
"id": 1,
"functions": [ 0, 1 ] },
{
"id": 39,
"functions": [ 0, 1, 3, 4 ]
},
{
"id": 41,
"functions": [ 0, 1 ]
}
]
const arr2 = [39, 41]
const result = arr1.filter(o => arr2.includes(o.id));
console.log(result)
You can create a Map to see whether there is an item of Map exists in filtering array. Getting an item from Map method is O(1):
const blocks = [
{
"id": 1,
"functions": [
0,
1
]
},
{
"id": 39,
"functions": [
0,
1,
3,
4
]
},
{
"id": 41,
"functions": [
0,
1
]
}
];
const arr2 = [39, 41];
const arr2Maps = new Map(arr2.map(a=>[a, a]));
const result = blocks.filter(o => arr2Maps.get(o.id));
console.log(result)
In addition, you can use filter and some methods. However, some method has O(n):
const blocks = [
{
"id": 1,
"functions": [
0,
1
]
},
{
"id": 39,
"functions": [
0,
1,
3,
4
]
},
{
"id": 41,
"functions": [
0,
1
]
}
];
const arr2 = [39, 41]
const result = blocks.filter(o => arr2.some(a=> a ==o.id ));
console.log(result)

Categories

Resources