Create Pagination in JavaScript using an Array of Objects - javascript

I have an Array of Objects.
let myArray = [
{ name: 'Product'; },
{ name: 'Product'; },
{ name: 'Product'; },
{ name: 'Product'; },
{ name: 'Product'; },
]
I want to paginate these objects. There should be two buttons on the webpage.
The first 5 objects should be shown. When the user clicks the 'next' button, these 5 objects should disappear. The next 5 objects should then be shown. Is it possible to do this using the .slice method. If so, how would I do this. I have looked online, but have not been able to find anything that helps me.

Related

Create Pagination in JavaScript with an Array using the slice method

How would I be able to create pagination in JavaScript using the slice method.
I have this Array:
let products = {
data: [
{
productName: "Product1",
},
{
productName: "Product2",
},
{
productName: "Product3",
},
{
productName: "Product4",
},
{
productName: "Product5",
},
{
multiple other products
},
],
};
I have looped through all of the products and displayed them on screen like this:
for (let i of products.data) {
let card = document.createElement("div");
let name = document.createElement("h5");
container.appendChild(name);
card.appendChild(container);
document.getElementById("products").appendChild(card);
}
I now want to create pagination. Each page should include a maximum of 10 products. I want to do this using the slice method.
I also want to create buttons on my website, which will be used for the pagination. The buttons should look similar to this.
How would I be able to create pagination in JavaScript using the slice method.
Example of how the pagination buttons should look

How to optimize two nested loops that create all possible combinations of items of two arrays [duplicate]

This question already has answers here:
Cartesian product of multiple arrays in JavaScript
(35 answers)
Closed 1 year ago.
The answer in Cartesian product of multiple arrays in JavaScript does not answer my question since my implementation is quite similar to what is said there and I'm only asking about ways to optimize this implementation.
I have two arrays of objects and I want to create one array of objects representing all possible combinations of the first two arrays. To make things clear let's say I have an array of products in supply, an array of products in demand, and I want to see every possible combination of supply and demand. I'm using node.js but the problem is language agnostic.
So if I have:
const supply = [
{
id: '1',
name: 'chair'
},
{
id: '2',
name: 'desk'
}
];
const demand = [
{
id: '3',
name: 'couch'
},
{
id: '4',
name: 'desks'
}
]
I want the output to be:
[
{
id: '1-3',
supply: 'chair',
demand: 'couch'
},
{
id: '1-4',
supply: 'chair',
demand: 'desks'
},
{
id: '2-3',
supply: 'desk',
demand: 'couch'
},
{
id: '2-4',
supply: 'desk',
demand: 'desks'
}
]
To achieve this I implemented the following:
return supply.reduce((acc, supply) => {
return acc.concat(
demand.map(demand => {
return {
id: `${supply.id}-${demand.id}`,
supply: supply.name,
demand: demand.name
}
})
)
}, []);
This works fine, but as my data sets get bigger (right now I have a couple of hundred items in each array, and I'm going to have more soon) it can also get very slow.
Is there any way to optimize this? I can't think of a way to achieve this without iterating over the one array and then over the other for each item of the first array. But maybe I'm missing something?
Please let know if I can provide more information on this.
Any help will be greatly appreciated!
The code can be greatly simplified to the following, which should be pretty quick.
demand.forEach((o, i) => {
acc.push(
{
id: `${supply[i].id}-${o.id}`,
supply: supply[i].name,
demand: o.name
})
})

Loop through an array of objects and get where object.field equals value

I'm currently working on a small application where I have to loop through an enormous array of objects. What would be the most efficient method to perform this?
var array = [
{
id: "1",
name: "Alpha"
},
{
id: "2",
name: "Beta"
},
...
];
I'd like to get each object where name equals "Alpha". I'm currently using a simple if statement to filter the objects with a different name value out, but I wonder if there's a more efficient way to do this, performance-wise.
It's worth to mention that I'll push the matching results into a new array.
No, there is no more efficient way.
The alternative is to build and maintain some kind of internal data structure which allows you to find the desired elements faster. As usual, the trade off is between the work involved in maintaining such a structure vs the time it saves you.
I don't have any way about which I would know it's more effective.
But if you had your objects ordered by name you could stop your search imideatly upon reaching an object whose name is not equal to "Alpha".
To find the first object you're looking for you can use binary search and from this Object you go up and down until at both ends you reach an object which isn't named "Alpha" or the end of array.
This is only a way of optimizing and will require time to sort the array and also will take more time when adding an element.
There's a JavaScript function exactly for this kind of task. Filter
From the Docs
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Here is a small example by code for getting all element from array which has a certain 'name' field:
const arr = [
{name: 'Abc'},
{name: 'Xyz'},
{name: 'Lmn'},
{name: 'Xyz'},
{name: 'Xyz'}
];
let response = findByName('Xyz');
console.log(response);
function findByName (name) {
return arr.filter((element) => {
return element.name = name;
});
}
If you need more than one time a collection with a given name, you could use an object with the names as hashes and have instantly access to the items.
var array = [{ id: "1", name: "Alpha" }, { id: "2", name: "Beta" }, { id: "3", name: "Beta" }, { id: "4", name: "Gamma" }, { id: "5", name: "Beta" }, { id: "2", name: "Alpha" }],
hash = Object.create(null);
array.forEach(function (a) {
if (!hash[a.name]) {
hash[a.name] = [];
}
hash[a.name].push(a);
});
console.log(hash);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to include elements of an array in another array?

So for example I have a MAIN array with all the information I need:
$scope.songs = [
{ title: 'Reggae', url:"#/app/mworkouts", id: 1 },
{ title: 'Chill', url:"#/app/browse", id: 2 },
{ title: 'Dubstep', url:"#/app/search", id: 3 },
{ title: 'Indie', url:"#/app/search", id: 4 },
{ title: 'Rap', url:"#/app/mworkouts", id: 5 },
{ title: 'Cowbell', url:"#/app/mworkouts", id: 6 }
];
I want to put only certain objects into another array without typing in each of the objects so the end result will look like
$scope.array1 = [
{ title: 'Reggae', url:"#/app/mworkouts",id: 1 },
{ title: 'Cowbell', url:"#/app/mworkouts",id: 6 }
];
I have tried this with no luck:
$scope.array1 = [
{ $scope.songs[1] },
{ $scope.songs[6] }
];
I will have to do a bunch of these so typing in each object would take forever, is there any faster way to do this? Thanks in advance :)
You need to do something like this:
$scope.array1 = $scope.songs.filter(function (song) {
return (song.title == "Reggae" || song.title == "Cowbell");
});
Here, the filter function will give you a filtered new array to be replaced for the original scope value.
Or in simple way, using the array indices, you can use:
$scope.array1 = [ $scope.songs[0] , $scope.songs[5] ];
You need to remove the braces since it's already an object. Although the array index starts from 0 so change index value based on 0.
$scope.array1 = [
$scope.songs[0] ,
$scope.songs[5]
];

Delete Object From A Value

I have a object, in that object I have other objects (objectseption). Now I want to be able to delete one of those objects (the objects within the main object) from a ID value given. I'll show you what I mean:
object {
1 : {
id: 1,
name: john
},
2: {
id: 3,
name: sam
},
3: {
id: 5,
name: ollie
},
4: {
id: 12,
name: nathan
}
}
Now let's say that I want to delete/remove Sam from the object, but all I have is Sam's ID. This is where I'm stuck. How do I remove Sam only having his ID (which is 3).
I'm quite new to javascript, and usually rely heavily on frameworks to complete a project - so when it comes to these simple things I get quite stuck!
Any Help would be greatly appreciated!
Iterate the objects properties, check, and remove:
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (obj[key].id == 3) {
delete obj[key];
}
}
}

Categories