How to immutably insert into a sorted array? [duplicate] - javascript

This question already has answers here:
Efficient way to insert a number into a sorted array of numbers?
(18 answers)
Closed 3 years ago.
How do I immutably insert an element into a sorted array? (Let's assume an array of integers for simplicity)
The reason for this question: I'm writing a reducer for a React app, where the order of elements in my particular array is important.
The closest solution I've found is this one here, but it doesn't cover insertions into a sorted array.

Try this one.
let sortedArr = [1,2,5,9,12];
const newItem = 7;
for (let i = 0; i < sortedArr.length; i++) {
if (newItem <= sortedArr[i]) {
sortedArr = [...sortedArr.slice(0, i), newItem, ...sortedArr.slice(i)];
break;
}
}
console.log(sortedArr);

Related

array.push() and splite in Array of arrays [duplicate]

This question already has answers here:
Split array into chunks
(73 answers)
Closed 6 days ago.
This post was edited and submitted for review 6 days ago.
I'm using arrayofArrays[0].push() inside a for loop in order to add an Object to the Array0 inside arrayofArrays.
Now I'd like that when Array0 has reached 2 element, the next element will be pushed to Array1, in order to achieve this situation:
var arrayofArrays = [[Obj0,Obj1],[Obj2,Obj3],[Obj4,Obj5], ...];
Sample code:
var arrayofArrays = [[]];
for(data in Data){
var Obj = {"field1":data[0], "field2":data[1], "field3":data[2] }
arrayofArrays[0].push(Obj); // need to pass to arrayofArrays[1] when arrayofArrays[0] has 2 Obj...
}
(I don't need to split an existing array, I'm adding Object to an array, and want them to split in sub-arrays while adding them)
Here is a functional programming approach to your question to unflatten an array:
const arr = Array.from(Array(6).keys()); // [0, 1, 2, 3...]
let t;
let arrOfArr = arr.map((v, idx) => {
if(idx % 2) {
return [t, v];
} else {
t = v;
return null;
}
}).filter(Boolean);
console.log({
arr,
arrOfArr,
});
Note: Array.from(Array(6).keys()) is just for demo. Replace this with any array of objects you like

How to save a list with dicts in cookies in JS? [duplicate]

This question already has answers here:
Sort array by firstname (alphabetically) in JavaScript [duplicate]
(23 answers)
Closed 1 year ago.
I have a list of data which contains some dicts.
data = []
data[0]['id']=5 data[0]['title']=''
data[1]['id']=6 data[1]['title']=''
data[2]['id']=4 data[2]['title']=''
data[3]['id']=0 data[3]['title']=''
data[4]['id']=9 data[4]['title']=''
data[5]['id']=1 data[5]['title']=''
Yep, I fixed everything. Thank you.
What about cookies?
How can I save my list in JS cookies?
Sorting can be done like this:
data.sort((a, b) => a.id - b.id);
Array.prototype.sort is your friend here. Your Array will be mutated this helper method so you may want to copy it first.
let data = [], ids = [5,6,4,0,9,1]
for (let i = 0; i < ids.length; i++) {
data.push({id: ids[i], title: ''})
}
const sorted = data.slice(0).sort((a,b)=>a.id - b.id)

In an array, how to make sure the elements don't repeat, in javascript? [duplicate]

This question already has answers here:
Remove duplicate values from JS array [duplicate]
(54 answers)
Closed 4 years ago.
I have this code, where the point is to read lottery numbers, and the numbers can not be smaller than 0, nor bigger than 49, nor can they repeat themselves. I don't understand how to put that in the while loop. How can I compare each number is inserted with the numbers previously inserted?
var totoloto=new Array(1);
for(var i=0; i<1; i++) {
totoloto[i]=new Array(5);
for(var j=0; j<5; j++) {
do {
totoloto[i][j] = parseInt(readLine("totoloto="));
} while (totoloto[i][j] < 1 || totoloto[i][j] > 49);
}
print(totoloto[i].toString().replaceAll(",", " "));
}
You can use Set instead of Array and just add values into set. If you don't know, Set contains only unique values.
Another way to do this is just using object:
let obj={}
obj.value1 = true // true is just for example. It doesn't make any sense
obj.value2 = true
// After getting all the keys you can
Object.keys(obj) // it returns all the keys in objecti i.e. your values
So, adding values with the same keys has no effect, because object can have only unique keys.

How to transform an array of arrays as rows into array of arrays as columns in JavaScript? [duplicate]

This question already has answers here:
Swap rows with columns (transposition) of a matrix in javascript [duplicate]
(5 answers)
Closed 7 years ago.
This question was incredibly hard for me to summarize in the title, so I'm sorry if it is misleading.
I have an array of arrays formatted like so:
array = [ [1,2,3,4,5,6,7,8,9],
[2,3,4,5,6,7,8,9,1],
[3,4,5,6,7,8,9,1,2],
[1,2,3,4,5,6,7,8,9],
[2,3,4,5,6,7,8,9,1],
[3,4,5,6,7,8,9,1,2],
[1,2,3,4,5,6,7,8,9],
[2,3,4,5,6,7,8,9,1],
[3,4,5,6,7,8,9,1,2]]
As you can see it's essentially a table with the subarrays as the rows in the table.
I want to create a function that takes the main array and essentially rotates it 90degrees clockwise. So the new subarrays are the first index of each array, the second index of each array, 3rd index of each array etc...
( I want my new main array to contain arrays of each column in this data set).
Thank you!
I have used temporary array newArray which will hold the resultant multidimensional array. (Assumption: as shown in question example, main array size and content-arrays' size should be same).
var newArray = [];
for(var i = 0; i < array.length; i++) {
for(var j= 0; j < array.length; j++) {
newArray[j] = newArray[j] || [];
newArray[j][i] = array[i][j];
}
}
console.log(newArray);

Sort an array in Javascript/JQuery [duplicate]

This question already has answers here:
How to sort an array of objects with jquery or javascript [duplicate]
(6 answers)
Closed 8 years ago.
There is an array emails having few attributes To, From, Subject, Description. I retrieve records from database and populate all rows in this array. I use to access all rows as follows:
for (var i = 0; i < emails.length; i++) {
var To = emails[i].To;
var Sender = emails[i].Sender;
var Subject = emails[i].Subject;
var Description = emails[i].Description;
}
Now I need to sort this array alphabetically by To values and store the sorted emails in another array sortedemails. How can I do this in easiest possible way in Javascript/JQuery?
Thanks.
Arrays in javascript have a sort function.
emails.sort(function(a, b) {
if (a.To < b.To) {
return -1;
} else {
return 1;
}
}
JavaScript arrays have a built-in .sort method. No loops (or jQuery needed).
emails.sort(function(a, b){
return a.To.localeCompare(b.To);
});
This will modify the email array. If you want to save the original (unsorted) array, you'll need to copy the array before sorting.
var sortedemails = emails.slice(0);
sortedemails.sort(function(a, b){
return a.To.localeCompare(b.To);
});

Categories

Resources