I am working on a small e-cart project(react project). While displaying the items, I am using rows.
I used fetch function to get all the product items. It is an array of objects having length of 20. I want to display the information in rows, each row consisting of 3 items information.
I tried to use map function of Array to map the items. But the problem I am facing is: After each iteration it should either jump to 3rd index or discard/remove the first 3 items.
So my question is can I present a new array in every iteration?
function ProdDisplay(){
const[bitData, setbitData]=useState(null);
fetch('https://fakestoreapi.com/products')
.then(result=>result.json())
.then(result=>setbitData(result))
return(
<div>
{bitData &&
bitData.map(()=>
<tr>
<td><IndProduct data={bitData[index]}/></td>
<td><IndProduct data={bitData[index+1]}/></td>
<td><IndProduct data={bitData[index+2]}/></td>
</tr>)
</div>
)
}
Here I want to skip 3 indices in every iteration or I want to reduce the array by 3 items every time. I tried Splice, it is not working. In each iteration, it has to produce a row consisting of 3 items.
Please help.
please use below foo
const sliceIntoChunks = (arr, chunkSize) => {
const res = [];
for (let i = 0; i < arr.length; i += chunkSize) {
const chunk = arr.slice(i, i + chunkSize);
res.push(chunk);
}
return res;
};
sliceIntoChunks(bitData, 3)
Example Code:
const bitData = [{
"id": 1,
"title": "Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops",
"price": 109.95,
"description": "Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday",
"category": "men's clothing",
"image": "https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg",
"rating": {
"rate": 3.9,
"count": 120
}
},
{
"id": 2,
"title": "Mens Casual Premium Slim Fit T-Shirts ",
"price": 22.3,
"description": "Slim-fitting style, contrast raglan long sleeve, three-button henley placket, light weight & soft fabric for breathable and comfortable wearing. And Solid stitched shirts with round neck made for durability and a great fit for casual fashion wear and diehard baseball fans. The Henley style round neckline includes a three-button placket.",
"category": "men's clothing",
"image": "https://fakestoreapi.com/img/71-3HjGNDUL._AC_SY879._SX._UX._SY._UY_.jpg",
"rating": {
"rate": 4.1,
"count": 259
}
},
{
"id": 3,
"title": "Mens Cotton Jacket",
"price": 55.99,
"description": "great outerwear jackets for Spring/Autumn/Winter, suitable for many occasions, such as working, hiking, camping, mountain/rock climbing, cycling, traveling or other outdoors. Good gift choice for you or your family member. A warm hearted love to Father, husband or son in this thanksgiving or Christmas Day.",
"category": "men's clothing",
"image": "https://fakestoreapi.com/img/71li-ujtlUL._AC_UX679_.jpg",
"rating": {
"rate": 4.7,
"count": 500
}
},
{
"id": 4,
"title": "Mens Casual Slim Fit",
"price": 15.99,
"description": "The color could be slightly different between on the screen and in practice. / Please note that body builds vary by person, therefore, detailed size information should be reviewed below on the product description.",
"category": "men's clothing",
"image": "https://fakestoreapi.com/img/71YXzeOuslL._AC_UY879_.jpg",
"rating": {
"rate": 2.1,
"count": 430
}
},
{
"id": 5,
"title": "John Hardy Women's Legends Naga Gold & Silver Dragon Station Chain Bracelet",
"price": 695,
"description": "From our Legends Collection, the Naga was inspired by the mythical water dragon that protects the ocean's pearl. Wear facing inward to be bestowed with love and abundance, or outward for protection.",
"category": "jewelery",
"image": "https://fakestoreapi.com/img/71pWzhdJNwL._AC_UL640_QL65_ML3_.jpg",
"rating": {
"rate": 4.6,
"count": 400
}
},
{
"id": 6,
"title": "Solid Gold Petite Micropave ",
"price": 168,
"description": "Satisfaction Guaranteed. Return or exchange any order within 30 days.Designed and sold by Hafeez Center in the United States. Satisfaction Guaranteed. Return or exchange any order within 30 days.",
"category": "jewelery",
"image": "https://fakestoreapi.com/img/61sbMiUnoGL._AC_UL640_QL65_ML3_.jpg",
"rating": {
"rate": 3.9,
"count": 70
}
},
{
"id": 7,
"title": "White Gold Plated Princess",
"price": 9.99,
"description": "Classic Created Wedding Engagement Solitaire Diamond Promise Ring for Her. Gifts to spoil your love more for Engagement, Wedding, Anniversary, Valentine's Day...",
"category": "jewelery",
"image": "https://fakestoreapi.com/img/71YAIFU48IL._AC_UL640_QL65_ML3_.jpg",
"rating": {
"rate": 3,
"count": 400
}
},
{
"id": 8,
"title": "Pierced Owl Rose Gold Plated Stainless Steel Double",
"price": 10.99,
"description": "Rose Gold Plated Double Flared Tunnel Plug Earrings. Made of 316L Stainless Steel",
"category": "jewelery",
"image": "https://fakestoreapi.com/img/51UDEzMJVpL._AC_UL640_QL65_ML3_.jpg",
"rating": {
"rate": 1.9,
"count": 100
}
},
{
"id": 9,
"title": "WD 2TB Elements Portable External Hard Drive - USB 3.0 ",
"price": 64,
"description": "USB 3.0 and USB 2.0 Compatibility Fast data transfers Improve PC Performance High Capacity; Compatibility Formatted NTFS for Windows 10, Windows 8.1, Windows 7; Reformatting may be required for other operating systems; Compatibility may vary depending on user’s hardware configuration and operating system",
"category": "electronics",
"image": "https://fakestoreapi.com/img/61IBBVJvSDL._AC_SY879_.jpg",
"rating": {
"rate": 3.3,
"count": 203
}
},
{
"id": 10,
"title": "SanDisk SSD PLUS 1TB Internal SSD - SATA III 6 Gb/s",
"price": 109,
"description": "Easy upgrade for faster boot up, shutdown, application load and response (As compared to 5400 RPM SATA 2.5” hard drive; Based on published specifications and internal benchmarking tests using PCMark vantage scores) Boosts burst write performance, making it ideal for typical PC workloads The perfect balance of performance and reliability Read/write speeds of up to 535MB/s/450MB/s (Based on internal testing; Performance may vary depending upon drive capacity, host device, OS and application.)",
"category": "electronics",
"image": "https://fakestoreapi.com/img/61U7T1koQqL._AC_SX679_.jpg",
"rating": {
"rate": 2.9,
"count": 470
}
},
{
"id": 11,
"title": "Silicon Power 256GB SSD 3D NAND A55 SLC Cache Performance Boost SATA III 2.5",
"price": 109,
"description": "3D NAND flash are applied to deliver high transfer speeds Remarkable transfer speeds that enable faster bootup and improved overall system performance. The advanced SLC Cache Technology allows performance boost and longer lifespan 7mm slim design suitable for Ultrabooks and Ultra-slim notebooks. Supports TRIM command, Garbage Collection technology, RAID, and ECC (Error Checking & Correction) to provide the optimized performance and enhanced reliability.",
"category": "electronics",
"image": "https://fakestoreapi.com/img/71kWymZ+c+L._AC_SX679_.jpg",
"rating": {
"rate": 4.8,
"count": 319
}
},
{
"id": 12,
"title": "WD 4TB Gaming Drive Works with Playstation 4 Portable External Hard Drive",
"price": 114,
"description": "Expand your PS4 gaming experience, Play anywhere Fast and easy, setup Sleek design with high capacity, 3-year manufacturer's limited warranty",
"category": "electronics",
"image": "https://fakestoreapi.com/img/61mtL65D4cL._AC_SX679_.jpg",
"rating": {
"rate": 4.8,
"count": 400
}
},
{
"id": 13,
"title": "Acer SB220Q bi 21.5 inches Full HD (1920 x 1080) IPS Ultra-Thin",
"price": 599,
"description": "21. 5 inches Full HD (1920 x 1080) widescreen IPS display And Radeon free Sync technology. No compatibility for VESA Mount Refresh Rate: 75Hz - Using HDMI port Zero-frame design | ultra-thin | 4ms response time | IPS panel Aspect ratio - 16: 9. Color Supported - 16. 7 million colors. Brightness - 250 nit Tilt angle -5 degree to 15 degree. Horizontal viewing angle-178 degree. Vertical viewing angle-178 degree 75 hertz",
"category": "electronics",
"image": "https://fakestoreapi.com/img/81QpkIctqPL._AC_SX679_.jpg",
"rating": {
"rate": 2.9,
"count": 250
}
},
{
"id": 14,
"title": "Samsung 49-Inch CHG90 144Hz Curved Gaming Monitor (LC49HG90DMNXZA) – Super Ultrawide Screen QLED ",
"price": 999.99,
"description": "49 INCH SUPER ULTRAWIDE 32:9 CURVED GAMING MONITOR with dual 27 inch screen side by side QUANTUM DOT (QLED) TECHNOLOGY, HDR support and factory calibration provides stunningly realistic and accurate color and contrast 144HZ HIGH REFRESH RATE and 1ms ultra fast response time work to eliminate motion blur, ghosting, and reduce input lag",
"category": "electronics",
"image": "https://fakestoreapi.com/img/81Zt42ioCgL._AC_SX679_.jpg",
"rating": {
"rate": 2.2,
"count": 140
}
},
{
"id": 15,
"title": "BIYLACLESEN Women's 3-in-1 Snowboard Jacket Winter Coats",
"price": 56.99,
"description": "Note:The Jackets is US standard size, Please choose size as your usual wear Material: 100% Polyester; Detachable Liner Fabric: Warm Fleece. Detachable Functional Liner: Skin Friendly, Lightweigt and Warm.Stand Collar Liner jacket, keep you warm in cold weather. Zippered Pockets: 2 Zippered Hand Pockets, 2 Zippered Pockets on Chest (enough to keep cards or keys)and 1 Hidden Pocket Inside.Zippered Hand Pockets and Hidden Pocket keep your things secure. Humanized Design: Adjustable and Detachable Hood and Adjustable cuff to prevent the wind and water,for a comfortable fit. 3 in 1 Detachable Design provide more convenience, you can separate the coat and inner as needed, or wear it together. It is suitable for different season and help you adapt to different climates",
"category": "women's clothing",
"image": "https://fakestoreapi.com/img/51Y5NI-I5jL._AC_UX679_.jpg",
"rating": {
"rate": 2.6,
"count": 235
}
},
{
"id": 16,
"title": "Lock and Love Women's Removable Hooded Faux Leather Moto Biker Jacket",
"price": 29.95,
"description": "100% POLYURETHANE(shell) 100% POLYESTER(lining) 75% POLYESTER 25% COTTON (SWEATER), Faux leather material for style and comfort / 2 pockets of front, 2-For-One Hooded denim style faux leather jacket, Button detail on waist / Detail stitching at sides, HAND WASH ONLY / DO NOT BLEACH / LINE DRY / DO NOT IRON",
"category": "women's clothing",
"image": "https://fakestoreapi.com/img/81XH0e8fefL._AC_UY879_.jpg",
"rating": {
"rate": 2.9,
"count": 340
}
},
{
"id": 17,
"title": "Rain Jacket Women Windbreaker Striped Climbing Raincoats",
"price": 39.99,
"description": "Lightweight perfet for trip or casual wear---Long sleeve with hooded, adjustable drawstring waist design. Button and zipper front closure raincoat, fully stripes Lined and The Raincoat has 2 side pockets are a good size to hold all kinds of things, it covers the hips, and the hood is generous but doesn't overdo it.Attached Cotton Lined Hood with Adjustable Drawstrings give it a real styled look.",
"category": "women's clothing",
"image": "https://fakestoreapi.com/img/71HblAHs5xL._AC_UY879_-2.jpg",
"rating": {
"rate": 3.8,
"count": 679
}
},
{
"id": 18,
"title": "MBJ Women's Solid Short Sleeve Boat Neck V ",
"price": 9.85,
"description": "95% RAYON 5% SPANDEX, Made in USA or Imported, Do Not Bleach, Lightweight fabric with great stretch for comfort, Ribbed on sleeves and neckline / Double stitching on bottom hem",
"category": "women's clothing",
"image": "https://fakestoreapi.com/img/71z3kpMAYsL._AC_UY879_.jpg",
"rating": {
"rate": 4.7,
"count": 130
}
},
{
"id": 19,
"title": "Opna Women's Short Sleeve Moisture",
"price": 7.95,
"description": "100% Polyester, Machine wash, 100% cationic polyester interlock, Machine Wash & Pre Shrunk for a Great Fit, Lightweight, roomy and highly breathable with moisture wicking fabric which helps to keep moisture away, Soft Lightweight Fabric with comfortable V-neck collar and a slimmer fit, delivers a sleek, more feminine silhouette and Added Comfort",
"category": "women's clothing",
"image": "https://fakestoreapi.com/img/51eg55uWmdL._AC_UX679_.jpg",
"rating": {
"rate": 4.5,
"count": 146
}
},
{
"id": 20,
"title": "DANVOUY Womens T Shirt Casual Cotton Short",
"price": 12.99,
"description": "95%Cotton,5%Spandex, Features: Casual, Short Sleeve, Letter Print,V-Neck,Fashion Tees, The fabric is soft and has some stretch., Occasion: Casual/Office/Beach/School/Home/Street. Season: Spring,Summer,Autumn,Winter.",
"category": "women's clothing",
"image": "https://fakestoreapi.com/img/61pHAEJ4NML._AC_UX679_.jpg",
"rating": {
"rate": 3.6,
"count": 145
}
}
]
const sliceIntoChunks = (arr, chunkSize) => {
const res = [];
for (let i = 0; i < arr.length; i += chunkSize) {
const chunk = arr.slice(i, i + chunkSize);
res.push(chunk);
}
return res;
};
console.log(sliceIntoChunks(bitData, 3));
Use with your code:
function ProdDisplay(){
const sliceIntoChunks = (arr, chunkSize) => {
const res = [];
for (let i = 0; i < arr.length; i += chunkSize) {
const chunk = arr.slice(i, i + chunkSize);
res.push(chunk);
}
return res;
};
const[bitData, setbitData]=useState(null);
fetch('https://fakestoreapi.com/products')
.then(result=>result.json())
.then(result=>setbitData(sliceIntoChunks(result, 3)))
return(
<div>
{bitData &&
bitData.map((item)=>
<tr>
<td><IndProduct data={item[0]}/></td>
<td><IndProduct data={item[1]}/></td>
<td><IndProduct data={item[2]}/></td>
</tr>)
</div>
)
}
I am working with a CosmosDB setup by one of my colleagues and connecting to it using a connection string. The database contains several JSON documents with the following schema:
{
"period": "Raw",
"source": "Traffic",
"batchId": "ee737270-0b72-49b7-a2f1-201f642e9c81",
"periodName": "Raw",
"sourceName": "Traffic",
"groupKey": "gc4151_a",
"partitionKey": "traffic-gc4151_a-raw-raw",
"time": "2021-08-05T23:55:10",
"minute": 55,
"hour": 23,
"day": 05,
"month": 08,
"quarter": 3,
"year": 2021,
"minEventTime": "2021-08-05T23:55:09",
"maxEventTime": "2021-08-05T23:55:11",
"meta": {
"siteId": "GC4151_A",
"from": {
"lat": "55.860894822588506",
"long": "-4.284365958508686"
},
"to": {
"lat": "55.86038667864348",
"long": "-4.2826901232101795"
}
},
"measurements": {
"flow": [
{
"calculation": "Raw",
"name": "flow",
"calculationName": "Raw",
"value": 0
}
],
"concentration": [
{
"calculation": "Raw",
"name": "concentration",
"calculationName": "Raw",
"value": 0
}
]
},
"added": "2021-08-05T12:21:32.000819Z",
"updated": "2021-08-05T12:21:32.000819Z",
"id": "d4346f50-543e-4c4d-82cf-835b480914c2",
"_rid": "4RRTAIYVA1AIAAAAAAAAAA==",
"_self": "dbs/4RRTAA==/colls/4RRTAIYVA1A=/docs/4RRTAIYVA1AIAAAAAAAAAA==/",
"_etag": "\"1c0015a1-0000-1100-0000-5f3fbc4c0000\"",
"_attachments": "attachments/",
"_ts": 1598012492
}
I am trying to write a SQL query to select all the records that fall between the current date-time and one week earlier, so I can use these to perform future calculations.
I have attempted to use both of the following:
SELECT *
FROM c
WHERE c.time > date_sub(now(), interval 1 week);
and
SELECT *
FROM c
WHERE c.time >= DATE_ADD(CURDATE(), INTERVAL -7 DAY);
However, both of these return the following error:
Gateway Failed to Retrieve Query Plan: Message: {"errors":[{"severity":"Error","location":{"start":124,"end":125},"code":"SC1001","message":"Syntax error, incorrect syntax near '1'."}]}
ActivityId: 51c3b6f7-e760-4062-bd80-8cc9f8de5352, Microsoft.Azure.Documents.Common/2.14.0, Microsoft.Azure.Documents.Common/2.14.0
My question is what is the issue with my code, and how can I fix it?
You may use DateTimeAdd and GetCurrentDateTime() to achieve this. Eg.
SELECT *
FROM c
WHERE c.time > DateTimeAdd("day",-7,GetCurrentDateTime() )
Let me know if this works for you.
I have a Array has given below. In this array some objects contain with Key catagoryName. For each seperate CategoryName i need to get the count where ReadDate is null.
QUESTIONS HIGHLIGHTED:
Push into Array based on each Category ( category names might be 'N' number ).
Get the each category count where ReadDate is null.
.controller('testController',function($scope,$rootScope){
$rootScope.messages = [
{
"IntMessageUserId": 9,
"ReadDate": null,
"MessageSubject": "HOLY CRAP ",
"MessageText": "blah blah blah",
"Priority": 1,
"PriorityDescription": "High",
"StartDate": "2017-01-19T00:00:00",
"EndDate": "2017-07-01T00:00:00",
"IntMessageCategoryId": 36,
"CategoryName": "a New Category By Dave",
"CategoryDescription": "Only a couple",
"ActiveSw": true
},
{
"IntMessageUserId": 110,
"ReadDate": "null",
"MessageSubject": "Test_chm2",
"MessageText": "Test_chm2",
"Priority": 2,
"PriorityDescription": "Urgent",
"StartDate": "2017-01-04T00:00:00",
"EndDate": "2017-06-02T00:00:00",
"IntMessageCategoryId": 39,
"CategoryName": "Alerts",
"CategoryDescription": "Alerts",
"ActiveSw": true
},
{
"IntMessageUserId": 117,
"ReadDate": "2017-05-05T06:35:00",
"MessageSubject": "Test_chm2",
"MessageText": "Test_chm2",
"Priority": 1,
"PriorityDescription": "High",
"StartDate": "2017-01-04T00:00:00",
"EndDate": "2017-06-02T00:00:00",
"IntMessageCategoryId": 39,
"CategoryName": "Alerts",
"CategoryDescription": "Alerts",
"ActiveSw": true
},
{
"IntMessageUserId": 113,
"ReadDate": "2017-05-03T08:48:00",
"MessageSubject": "Testing PSC",
"MessageText": "Psc note that displays until May 26",
"Priority": 1,
"PriorityDescription": "High",
"StartDate": "2017-04-24T09:31:00",
"EndDate": "2017-05-26T09:31:00",
"IntMessageCategoryId": 59,
"CategoryName": "Alerts PSC",
"CategoryDescription": "Alerts PSC",
"ActiveSw": true
},
{
"IntMessageUserId": 130,
"ReadDate": null,
"MessageSubject": "17/18 Parking Pass sale dates",
"MessageText": "Parking Passes will be available for purchase for the 17/18 school year for all current Juniors starting on June 1st. Sophomores may purchase passes starting on August 1st. Sales are in person only at the school district offices. You must fill out our parking permit form, Show your current drivers license, and proof of insurance. Passes will be sold for $50.00 for the school year. \r\n\r\n",
"Priority": 0,
"PriorityDescription": "Normal",
"StartDate": "2017-05-05T10:40:00",
"EndDate": "2017-06-01T10:39:00",
"IntMessageCategoryId": 67,
"CategoryName": "High School Students",
"CategoryDescription": "High School students",
"ActiveSw": true
},
{
"IntMessageUserId": 111,
"ReadDate": "2017-05-03T08:50:00",
"MessageSubject": "Summer Sports Camps",
"MessageText": "Our summer sports camps flyers will be sent home in the next week or 2. Please check them out and see if you would like to enroll your child in a sports camp program. We encourage them to try something new, or improve their skills in an existing sport. ",
"Priority": 0,
"PriorityDescription": "Normal",
"StartDate": "2017-03-21T00:00:00",
"EndDate": "2017-05-15T00:00:00",
"IntMessageCategoryId": 69,
"CategoryName": "Athletic Department Notifications ",
"CategoryDescription": "Athletic Department.",
"ActiveSw": false
},
{
"IntMessageUserId": 131,
"ReadDate": null,
"MessageSubject": "End of Year Lunch balances",
"MessageText": "As we come to the end of our school year, a reminder that unused lunch funds will roll over to next school year and be available next year in the lunch line. If you have a student who is graduating and has unused funds, please consider donating those funds to a student in need.. You can contact the Food Service department at 513-555-5555 and we will be happy to coordinate this. Refunds of unused lunch funds can be issued for any student who's balance is greater than $5.00 Please fill out a refund form at the school office and they will be processed by our accounting department. Refund checks will be mailed within 30 days of receiving your forms in the office. Have a great summer. ",
"Priority": 0,
"PriorityDescription": "Normal",
"StartDate": "2017-05-05T10:45:00",
"EndDate": "2017-06-09T10:45:00",
"IntMessageCategoryId": 80,
"CategoryName": "Nutrition Services",
"CategoryDescription": "Nutrition Services",
"ActiveSw": true
}
];
What i tried till.
angular.forEach($rootScope.messages,function(value, key){
$scope.checkUnreadMessages(value.CategoryName);
})
var mainArray = [];
$scope.call = function(){
angular.forEach(arr, function(value, key){
var subarr = [];
subarr[value] = [];
angular.forEach($rootScope.messages, function(v, k){
if(value == v.CategoryName){
subarr[value].push(v.ReadDate);
}
})
mainArray.push(subarr);
})
}
I generally don't like to use extra library for a simple job which can be easily done in pure javascript.
https://repl.it/Hk45/2
Here is a link to a javascript compiler where you can see a solution.
Notice that all the work is done by the very simple function :
function fillOrInitiate(category, element){
if(categories[category]){
categories[category].push(element);
} else {
categories[category] = [];
categories[category].push(element);
}
}
Then just iterate through your data.
EDIT : Take care of your data, sometimes ReadDate is null and sometimes it is "null". However I took care of that in my example in the function CountReadDateNull.
You should not be able to visualize the data directly by printing final tab, but it is here as you can see on the second console.log
Why you are not using Underscore.js
Need to Extract Array Based on Category Name.
_.where( $rootScope.messages, {CategoryName: "searching category name"});
Get the each category count where ReadDate is null.
_.where( $rootScope.messages, {ReadDate: null}).length;
1) Iterate through an array of messages and check the same category name and then pushing it into new array, before that you need to group it using category name as the key.
var groupCategory = {};
angular.forEach($rootScope.messages, function (oldVal, newVal) {
if (oldVal.CategoryName === newVal.CategoryName) {
if (angular.isDefined(groupCategory[newVal.CategoryName])) {
groupCategory[newVal.CategoryName].push(newVal);
} else {
groupCategory[newVal.CategoryName] = [newVal];
}
}
});
2) Then, you can count the category group by filter/checking if ReadDate is null
var cnt = 0;
angular.forEach(sameCategoryObj, function (val) {
if(val.ReadDate === null) {
cnt++;
}
});