Add new items and slice from the top Javascript - javascript

I have a list with items like:
var values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...];
I want, for every scroll, to add 15th new items and then to slice from the top another 15th elements.
Can you help me? Thanks!!!
Updated:
getMoreItems(items: any) {
var lastIndex: number;
if (items.visible.length) {
var lastItem: any = _.last(items.visible);
lastIndex = _.findLastIndex(items.allValues, { Name: lastItem.Name });
}
var startIndex = lastIndex + 1 || 0;
var endIndex = Math.min(startIndex + 15, items.allValues.length);
var newItems = items.allValues.slice(startIndex, endIndex);
if (items.visible.length > 30) {
items.visible = items.visible.slice(0, 15).concat(newItems);
} else {
items.visible = items.visible.concat(newItems);
}
}

var values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...];
values = values.splice(0,15); // remove first 15 items
values = values.concat([another 15 items]); // add next 15
And of course you can inline this:
values = values.splice(0,15).concat([x1...x2])

Something like this?
var numbers = [1,2,3,4,5,6,7,8,9,10];
numbers = numbers.slice(2).concat([11,12]);
console.log(numbers);
>> [ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]

if you have array on scroll you can reinitialize your array:
var old= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
scroll=[32, 232,23, 232, 23, 232, 23,238, 92, 120];
old=scroll;
console.log(old);
and if you ahve items one by one then you can use pattern:
if you have array on scroll you can reinitialize your array:
var old= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
old.push(next_value);
old.shift()
console.log(old);

Related

Splitting an array into 3 unequal arrays in JavaScript

Suppose I have an array of
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
And I want to split it in 3, with two arrays containing the first and last X elements of the original array, and the third array containing the remaining elements, like so:
#1 - [0, 1, 2]
#2 - [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
#3 - [13, 14, 15]
Is there a shorter/better way of doing that instead of:
const splitBy = 3;
const originalArray = Array.from(Array(16).keys());
const result = [
originalArray.slice(0, splitBy),
originalArray.slice(splitBy, -splitBy),
originalArray.slice(-splitBy),
];
console.log(result)
"better" is subjective... however, if you need this more than once, a generic function could be an option:
function multiSlice(a, ...slices) {
let res = [], i = 0
for (let s of slices) {
res.push(a.slice(i, s))
i = s
}
res.push(a.slice(i))
return res
}
// for example,
const originalArray = Array.from(Array(16).keys());
console.log(multiSlice(originalArray, 3, -3))
console.log(multiSlice(originalArray, 2, 5, 10, 12))

Change array list into multiple array lists every 3 items

I want to filter a large array list into multiple arrays for every 5 items in a certain way so that [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] would be [[1, 2, [3, 4, 5]], [6, 7, [8, 9, 10]]] or [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] would be [[1, 2, [3, 4, 5]], [6, 7, [8, 9, 10]], [11, 12, [13, 14, 15]]]. (All arrays will be a multiple of 5 in my program.)
How would I do this?
Right now I'm doing this
for (var i = 1; i < (stoneTextureUnfiltered.length+1)/1.01; i++) {
stoneTexture.push([stoneTextureUnfiltered[i], stoneTextureUnfiltered[i+1], stoneTextureUnfiltered[i+2], [stoneTextureUnfiltered[i+3], stoneTextureUnfiltered[i+4], stoneTextureUnfiltered[i+5]]]);
}
but it doesn't seem to be working.
Thanks,
-Voxel
Assuming you've chunked the array already into parts of 5 with these answers and it's stored in a variable named chunks, to wrap the last 3 in each chunk you can use map:
const final = chunks.map((chunk) => [chunk[0], chunk[1], chunk.slice(2)]);
You add the first and second elements to the new list, then add the rest of the chunk as a whole.
Demo below:
// using second answer
var perChunk = 5 // items per chunk
var inputArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
var chunks = inputArray.reduce((resultArray, item, index) => {
const chunkIndex = Math.floor(index/perChunk)
if(!resultArray[chunkIndex]) {
resultArray[chunkIndex] = [] // start a new chunk
}
resultArray[chunkIndex].push(item)
return resultArray
}, [])
// answer below
const final = chunks.map((chunk) => [chunk[0], chunk[1], chunk.slice(2)]);
console.log(final);
As you can see, it works nicely!

convert 9x9 array into 9 (3x3) array in javascript?

convert 9x9 array into 9 (3x3) array in javascript?
i have written the code, but its not pushing the 3x3's into separate array.
i want 9 3x3 arrays
let array =
[
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[2, 3, 1, 5, 6, 4, 8, 9, 7],
[3, 1, 2, 6, 4, 5, 9, 7, 8],
[4, 5, 6, 7, 8, 9, 1, 2, 3],
[5, 6, 4, 8, 9, 7, 2, 3, 1],
[6, 4, 5, 9, 7, 8, 3, 1, 2],
[7, 8, 9, 1, 2, 3, 4, 5, 6],
[8, 9, 7, 2, 3, 1, 5, 6, 4],
[9, 7, 8, 3, 1, 2, 6, 4, 5]
];
let final=[];
let row = [0,1,2];
let col = [0,1,2];
let counter = 0;
for ( let i = 0 ; i <= array.length - 1 ; i += 3 )
{
for(let j = 0 ; j <= array.length - 1 ; j += 3 )
{
final.push([]);
row.forEach( ele1 => {
final[counter].push([])
col.forEach( ele2 => {
final[counter][ele1].push(array[ele1+i][ele2+j]);
})
})
counter+=1;
}
}
console.log(final)
You can loop through the array using map function and check for the index values to break into arrays as required.
let myArr =[[1, 2, 3, 4, 5, 6, 7, 8, 9],
[2, 3, 1, 5, 6, 4, 8, 9, 7],
[3, 1, 2, 6, 4, 5, 9, 7, 8],
[4, 5, 6, 7, 8, 9, 1, 2, 3],
[5, 6, 4, 8, 9, 7, 2, 3, 1],
[6, 4, 5, 9, 7, 8, 3, 1, 2],
[7, 8, 9, 1, 2, 3, 4, 5, 6],
[8, 9, 7, 2, 3, 1, 5, 6, 4],
[9, 7, 8, 3, 1, 2, 6, 4, 5]];
let newArr = convertTo3x3(myArr);
console.log(newArr);
function convertTo3x3(myArr){
let array3x3 = [];
myArr.map((row, rIndex) => {
let tempArr = [];
let row3 = [];
row.map((item, lIndex) => {
// convert each row to 3x3 rows
if(lIndex % 3 == 0){
// reset row3 for new 3x3 arr on every 1st item of 3x3
row3 = [];
}
row3.push(item);
if(lIndex % 3 == 2){
// push 3x3 row to tempArr on every 3rd item of 3x3
tempArr.push(row3);
}
});
array3x3.push(tempArr);
});
return array3x3;
}
Your code seems to work fine, but if you want a more javascriptey code, that performs worse, here you go.
let array = [
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[2, 3, 1, 5, 6, 4, 8, 9, 7],
[3, 1, 2, 6, 4, 5, 9, 7, 8],
[4, 5, 6, 7, 8, 9, 1, 2, 3],
[5, 6, 4, 8, 9, 7, 2, 3, 1],
[6, 4, 5, 9, 7, 8, 3, 1, 2],
[7, 8, 9, 1, 2, 3, 4, 5, 6],
[8, 9, 7, 2, 3, 1, 5, 6, 4],
[9, 7, 8, 3, 1, 2, 6, 4, 5],
];
let final = [];
array
.reduce((a, c) => {
const chunk = (arr, n) =>
arr.length ? [arr.slice(0, n), ...chunk(arr.slice(n), n)] : [];
return [...a, ...chunk(c, 3)];
}, [])
.map((el, i) => {
if (i % 3 == 0) {
final = [...final, [el]];
} else {
final[Math.floor(i / 3)] = [...final[Math.floor(i / 3)], el];
}
});
console.log(final);
Your code is trying to do too much. Make it difficult to understand.
I would first break it up. Write a simple function than knows how to take an array-of-arrays and return an arbitrary rectangular selection from it. Something like this, that's easy to test:
/**
* Snip a rectangular section of an array of arrays (ragged, 2D array).
* The returned array-of-arrys will ALWAYS be the specified size, padded
* with 'undefined' values to the specified size.
*
* #param {Object[][]} arr - An array of arrays (ragged 2D array)
* #param {number} row - Origin row: {row,col} denotes the upper-left corner of the rectangle to snip
* #param {number} col - Origin column: {row,col} denotes the upper-left corner of the rectangle to snip
* #param {number} nrows - Number of rows to snip
* #param {number} ncols - Nunber of columns to snip
*
* #returns {Object[][]}
*/
function snip(arr, row, col, nrows, ncols ) {
const selection = [];
for ( let r = row, i = 0 ; r < row+nrows ; ++r, ++i ) {
selection[i] = [];
const tmp = arr[r] ?? [];
for ( let c = col, j = 0 ; c < col+ncols ; ++c, ++j ) {
selection[i][j] = tmp[c];
}
}
return selection;
}
Once you have that, then chopping up your larger array-of-arrays into 3x3 arrays is easy.
This code starts at the top left corner or your 9x9 array and returns a flat list containing 9 separate 3x3 arrays, chopped out left-to-right and top-to-bottom:
final = [];
for ( let x = 0 ; x < 9; x += 3 ) {
for ( let y = 0 ; y < 9 ; y += 3 ) {
// (x,y) denotes the top left corner of the desired sub-array
final.push( snip(arr, x,y, 3,3 ) );
}
}
The nice thing about this approach is that it is easy to test, and
.
.
.
It's flexible. It can handle a source array of any size, and you can chop it up into subarrays of any size and in any order, whatever you see fit to do.

Array Methods in javascripts

I don't understand this method of pop and unshift in this array
let nums = [1, 2, 3, 6, 9, 8, 7, 4];
const ids = [1, 2, 3, 6, 9, 8, 7, 4];
let btn5 = document.getElementById("btn5");
btn5.onclick = function() {
nums.unshift(nums.pop());
for (i = 0; i <= 7; i++) {
document.getElementById("btn" + ids[i]).innerHTML = nums[i];
}
}
nums.unshift(nums.pop()); is:
// Remove the last entry from the array
const tmp = nums.pop();
// Insert it at the beginning of the array
nums.unshift(tmp);
So for instance, the first time that runs, nums starts with:
[1, 2, 3, 6, 9, 8, 7, 4]
so pop removes the 4 from the end, and inserts it at the beginning:
[4, 1, 2, 3, 6, 9, 8, 7]
Live Example:
const nums = [1, 2, 3, 6, 9, 8, 7, 4];
console.log("before:", JSON.stringify(nums));
nums.unshift(nums.pop());
console.log("after: ", JSON.stringify(nums));
Details on MDN: pop, unshift.
Array pop method removes and return last element of an array. If you write something like,
let nums = [1, 2, 3, 6, 9, 8, 7, 4];
const ids = [1, 2, 3, 6, 9, 8, 7, 4];
const poppedValue = nums.pop(); //poppedValue = 4 and nums = [1, 2, 3, 6, 9, 8, 7]
And unshift method push the item at the beginning of the array.
nums.unshift(poppedValue); // nums = [4, 1, 2, 3, 6, 9, 8, 7];

How object hash works to remove duplicates in this scenario?

function distinctUnion(arr, arr2) {
let merged = [...arr, ...arr2];
var result = [];
var map = {}
for (let i = 0; i < merged.length; i++) {
if (!map.hasOwnProperty(merged[i])) {
map[merged[i]] = true; // Line 3 --> if I remove this line, it prints duplicates
console.log('map', JSON.stringify(map, 2, null));
result.push(merged[i]);
}
}
return result;
}
let arr = [3, 4, 5, 6, 6, 4, 5, 8, 9, 10, 10];
let arr2 = [11, 11, 11, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6];
console.log('unique ', JSON.stringify(distinctUnion(arr, arr2), 2, null));
All we are setting here is map[merged[i]] = true; for all keys in object
map {"3":true,"4":true,"5":true,"6":true,"8":true,"9":true,"10":true,"11":true}
then how result.push(merged[i]) has only unique values?
I mean to say merged[i] inside loop should still have all array values including duplicates right?
I am not able to understand the link between map[merged[i]] = true; and result.push(merged[i])
If you do not set the property to anything, map.hasOwnProperty(...) will spuriously return false for the next time that value is encountered, thus allowing duplicates. You don't need to set it to true, as it is just used to indicate the presence of a key; any value is fineā€”even undefined!
function distinctUnion(arr, arr2) {
let merged = [...arr, ...arr2];
var result = [];
var map = {}
for (let i = 0; i < merged.length; i++) {
if (!map.hasOwnProperty(merged[i])) {
map[merged[i]] = undefined;
result.push(merged[i]);
}
}
return result;
}
let arr = [3, 4, 5, 6, 6, 4, 5, 8, 9, 10, 10];
let arr2 = [11, 11, 11, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6];
console.log('unique ', JSON.stringify(distinctUnion(arr, arr2), 2, null));
To make your code works, you just need to replace map[merged[i]] = true; with map[merged[i]] = undefined;.
However, you can make your function more simplified as follows:
function distinctUnion(arr, arr2) {
let map = {};
[...arr, ...arr2].forEach((x)=>{map[x] = x});
return Object.values(map);;
}
let arr = [3, 4, 5, 6, 6, 4, 5, 8, 9, 10, 10];
let arr2 = [11, 11, 11, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6];
console.log('Unique ', distinctUnion(arr, arr2));

Categories