How can we modify javascript array to array object? - javascript

I have this array arr = [{id:1},{id:2},{id:3},{id:5},{id:5}]
I want to modify array like index 0 - 1 is first, 2 -3 is second, 4 - 5 is third and so on
Result array:
[first:[{id:1},{id:2}],second:[{id:3},{id:5}],third:[{id:5}]]
How can I modify array in such type?

The result you are expecting is not a valid array.
[first: [{},{}]]
It should be either an array like this
[[{},{}],[{},{}]]
or an object
{"first":[{},{}],"second":[{},{}]}
The code below converts your input to an array, it can be easily modified to an object if that's what you are looking for with some small modifications.
const arr = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 5 }, { id: 5 }];
let result = arr.reduce((acc, current, index) => {
if (index % 2 == 0) {
acc.push([current]);
} else {
acc[Math.floor(index / 2)].push(current);
}
return acc;
}, []);

You can use array.prototype.map. This example returns the id value of each multiplied by the number it exists in the array.
let arr = [{id:1},{id:2},{id:3},{id:5},{id:5}];
arr.map(function(item,index) {
return item.id * index;
})
Try it out!

Related

How to create array of objects through map?

I would like to have multiple arrays of objects like this.
E.g:
const pets = [
{
name: "cat",
age: 4
},
{
name: "dog",
age: 6
}
]
But I want to create it using a map. So I was trying something like this.
let pets = [];
pets.map((item) => {
return (
item.push({
name: "cat",
age: 4
}, {
name: "dog",
age: 6
})
)
})
By this method, I'm getting an empty array.
So assuming this is incorrect, how would I go on and make this through a map.
Please any help would be appreciated.
first of all map works by looping through an array but you have empty array let pets = []; so the loop doesn't even start ! that's why you are getting empty array
Secondly map essentially is a method through which we can create a new array with the help of an existing array so you have chosen a wrong way!
example of map
const fruits = ["Mango", "Apple", "Banana", "Pineapple", "Orange"];
console.log(fruits);
const uppercaseFruits = fruits.map((fruit)=>{
return fruit.toUpperCase(); // this thing will be added to new array in every iteration
});
console.log(uppercaseFruits);
but still ....
let pets = [""]; // an item so that loop can start
const myPets = pets.map((item) => {
return (
([{
name: "cat",
age: 4
},{
name: "dog",
age: 6
}])
)
})
console.log(myPets)
//Usage of map: for example
let array = [1, 2, 3, 4, 5];
let newArray = array.map((item) => {
return item * item;
})
console.log(newArray) // [1, 4, 9, 16, 25]
map will not change the original array, if you don't assign a value to it, the original array will never be affected
And if you want to get what you want you use RANDOM like this
//random String
function randomString(e) {
e = e || 32;
var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
a = t.length,
n = "";
for (i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
return n
}
//random Number
function GetRandomNum(Min,Max)
{
var Range = Max - Min;
var Rand = Math.random();
return(Min + Math.round(Rand * Range));
}
var num = GetRandomNum(10000,999999);
alert(num);
Then you can combine random strings and random numbers into a new Object through a function

JS Create array of objects containing random unique numbers

In javascript I want to create an array of 20 objects containing 2 random numbers between 1 and 250. All numbers in the array I want to be unique from each other. Basically like this:
const matches = [
{ player1: 1, player2: 2 },
{ player1: 3, player2: 4 },
{ player1: 5, player2: 6 },
{ player1: 7, player2: 8 },
...
]
// all unique numbers
I have found this other method
const indexes = [];
while (indexes.length <= 8) {
const index = Math.floor(Math.random() * 249) + 1;
if (indexes.indexOf(index) === -1) indexes.push(index);
}
But this only returns an array of numbers:
[1, 2, 3, 4, 5, 6, 7, 8, ...]
You could use Array.from method to create an array of objects and then also create custom function that will use while loop and Set to generate random numbers.
const set = new Set()
function getRandom() {
let result = null;
while (!result) {
let n = parseInt(Math.random() * 250)
if (set.has(n)) continue
else set.add(result = n)
}
return result
}
const result = Array.from(Array(20), () => ({
player1: getRandom(),
player2: getRandom()
}))
console.log(result)
You can create an array of 251 elements (0-250) and preset all values to 0 to keep track of the generated elements. Once a value is generated, you mark that value in the array as 1.
Check below:
// create an array of 251 elements (0-250) and set the values to 0
let array = Array.from({ length: 251 }, () => 0);
let matches = [];
function getRandomUniqueInt() {
// generate untill we find a value which hasn't already been generated
do {
var num = Math.floor(Math.random() * 249) + 1;
} while(array[num] !== 0);
// mark the value as generated
array[num] = 1;
return num;
}
while (matches.length <= 4) {
let obj = { "player1" : getRandomUniqueInt(), "player2" : getRandomUniqueInt() };
matches.push(obj);
}
console.log(matches);

How to get lastindexof an array using key value pair [duplicate]

This question already has answers here:
indexOf method in an object array?
(29 answers)
Closed 3 years ago.
I am trying to get the last index of a value in an array of objects.
I am unable to make it work; I am expecting the lastIndexOf an element id with value 0.
var sample = [
{
id: 0,
name: 'abbay',
rank: 120
},
{
id: 1,
name: 'sally',
rank: 12
},
{
id: 0,
name: 'abbay',
rank: 129
}
];
var index = this.sample.lastIndexOf(0{id});
Argument of type '0' is not assignable to parameter of type '{id: number; name: string; rank: number;}'.
You can map into an array of booleans:
var lastIndex =sample.map(s =>
s.id === 0).lastIndexOf(true);
then access your array by last index:
console.log(sample[lastIndex]);
Array's lastIndexOf method compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator). If your array contains objects, then you have to use another method.
If performance is not important and the amount of data is not that big, you can use
const lastIndex = sample.length - 1 - sample
.slice()
.reverse()
.findIndex( item => item.id === 0 );
slice will create a copy of the array, reverse will reverse it, findIndex will return the first item that matches o.id === 0 and the final result is subtracted from sample.length - 1. It's not very efficient for a large data set.
Or you can use a plain for
function findLastIndexOf(arr) {
for (let i = arr.length; i--;) {
if (arr[i].id === 0) {
return i;
}
}
}
findLastIndexOf(sample);
for (let i = arr.length; i--;) looks weird but it will start iterating from the last position and stop when i reach the value of 0. Give it a try.
Hope it helps
Try this:
const lastIndex = sample.map(res=>res.id).lastIndexOf(0) // id = 0
console.log(lastIndex) // 2
const lastIndexWithIdZero = this.sample.length - this.sample.reverse().findIndex(i => i.id === 0);
if (lastIndexWithIdZero > arrLen) {
throw new Error('didn\'t worked');
}
forget that, it's slow, better use just
let lastIndexWithIdZero = -1;
for (let i = 0, v; v = sample[i]; i++) {
if (v.id === 0) {
lastIndexWithIdZero = i;
}
}
console.log(lastIndexWithIdZero);
http://jsben.ch/LY1Q0
You could filter the results, then reverse the results and grab the first item.
const sample = [{
id: 0,
name: "abbay",
rank: 120
},
{
id: 1,
name: "sally",
rank: 12
},
{
id: 0,
name: "abbay",
rank: 129
}
]
console.log(
sample
// Add the index to the object
.map((i, idx) => ({id: i.id, idx}))
// Filter the object where id == 0
.filter(i => i.id == 0)
// Reverse the result and get the first item
// Get the idx
.reverse()[0].idx
)

Array reduce on javascript return wrong values with array chainability

I'm trying to get some math on an array of objects. Using the map for getting the value inside of the object and then reduce for made the calcules. For some reason reduce not return the correct value.
This is an example:
var test = [{
id: 1,
value: 2
}];
var newe = test.map((x) => x.value).reduce(function(total, sum) {
console.log([total, sum]);
return total + (sum * 2);
});
It's supposed to return 4, however, it returns 2.
Do you have an idea what is wrong? I share the code on jsfiddle https://jsfiddle.net/dleo7/ckgnrubh/10/
Doc from MDN
If initialValue isn't provided, reduce() will execute the callback function starting at index 1, skipping the first index. If initialValue is provided, it will start at index 0.
So, basically, your approach is skipping the first index 0 and the first value is returned 2. To solve this, you need to pass the initialValue, in this case, 0.
var test = [{
id: 1,
value: 2
}];
var newe = test.map((x) => x.value).reduce(function(total, sum) {
return total + (sum * 2);
}, 0);
// ^
// |
// +---- InitialValue
console.log(newe);
.as-console-wrapper { max-height: 100% !important; top: 0; }
you should pass initial value to reduce function,
var test = [{
id: 1,
value: 2
}];
var newe = test.map((x) => x.value).reduce(function(total, sum) {
console.log([total, sum]);
return total + (sum * 2);
}, 0);
document.getElementById('output').innerHTML = newe;

looping through object and mapping to a new object in a specific order

I have a variable that looks like this:
var objList = [{variantId: "1111", quantity: 2},
{variantId: "222222", quantity: 2},
{variantId: "333333", quantity: 2},
{variantId: "44444", quantity: 1}]
I am looking to write a function that takes in a number between 1 and all of the quantities added together ( in this example 7 ) then it will contstruct a new variable that has a total quantity of the input
Items will be added in this order:
variantId:1111 - add one of these to the new variable
variantId:2222 - add one of these ""
variantId:3333 - add on of these ""
variantID:4444 - add the only one of these
variantID:1111 - add the second one of these to new variable
variantID:2222 - add the second one of these ""
variantID:3333 - add the second one of these ""
the function will look something like this.
function(x){
var newObj = [];
var i=0;
while(i<x){
//logic to add the necessary item from the objList
// really struggling here
i++;
}
return newObj;
}
Iterate the array while you still have space in your inventory
Check that the current item still has quantity
If it doesn't, skip it
If it does, decrement the item's quantity and add that item to inventory
Return the inventory
Consider this code:
const objList = [{
variantId: "1111",
quantity: 1
},
{
variantId: "222222",
quantity: 2
},
{
variantId: "333333",
quantity: 2
},
{
variantId: "44444",
quantity: 1
}
];
function distribute(list, count) {
// Track our distributed items
const ret = [];
// Clone and reverse the array input the array for good measure
let clone = list
.map(item => Object.assign({}, item))
.reverse();
// Start idx at the "begining"
let idx = clone.length - 1;
// Iterate through the inventory while we have room and items
while (count-- && clone.length) {
// Push the current item
ret.push(clone[idx].variantId);
// Decrement the quantity of items
clone[idx].quantity--;
// If we are out of the item, remove it
if (!clone[idx].quantity) {
clone.splice(idx, 1);
}
// Go to the next item
idx--;
// If we reach the "end" of the inventory
if (!idx) {
// Go back to the "begining"
idx = clone.length - 1;
}
}
// Return our parceled items
return ret;
}
// Test it
console.log(distribute(objList, 5))

Categories

Resources