This question already has answers here:
Split array into chunks
(73 answers)
Closed 5 years ago.
Assuming I have an integer n which is greater than 0, and an array like this:
var array = [1, 2, 5, 6, 8, 9, 12, 13, 17...] //random values
How would I iterate through this array, going through and getting values n at a time (and putting it into a 2D array as well)?
If n were 3, for example, I would want a return value of
[[1, 2, 5], [6, 8, 9], [12, 13, 17]...]
And the code would be like this:
var array = [];
for (var i = 0; i < array.length; i += 3) {
var first = array[i];
var second = array[i+1];
var third = array[i+2];
array.push([
first, second, third
]);
}
Problem with this is that I have fixed values to get my objects by (the i, i+1, etc.)
If I have an unknown integer, then incrementing right up to n will not work.
How would I go about achieving this?
Use slice to take chunks and go through the array:
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const partition = (n, arr) => {
const result = [];
let i = 0;
while(i < arr.length) {
result.push(arr.slice(i, i + n));
i = i + n;
}
return result;
};
console.log(partition(1, arr));
console.log(partition(2, arr));
console.log(partition(3, arr));
console.log(partition(4, arr));
Related
This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Simplest code for array intersection in javascript
(40 answers)
Closed 1 year ago.
I wanted to compare two array and store the element that is present in both array into a new array. So I write this code but it didn't work.
var sampleArray = [1, 2, 3, 4, 5, 6, 7];
var sampleArray2 = [5, 6, 7, 8, 9, 10 ,11];
var similarElements =[];
for (let i = 0; i < sampleArray.length; i++) {
for (let j = 0; j < sampleArray2.length; j++) {
if (sampleArray[i] === sampleArray2[j]) {
similarElements.push();
}
}
}
console.log(similarElements);
let arr1 = [1, 2, 3, 4, 5, 6, 7];
arr2 = [5, 6, 7, 8, 9, 10 ,11];
hash = arr1.reduce((h,e)=> (h[e]=1, h), {}), //iterate first array once
common = arr2.filter(v=>hash[v]); //iterate secod array once
console.log('Cpmmon elements: ', common);
It searches for itself in sampleArray2, if it finds itself it'll add the number to similarArray
var sampleArray = [1, 2, 3, 4, 5, 6, 7];
var similarArray = [];
for (const num of sampleArray) {
if (sampleArray2.indexOf(num) {
similarArray.push(num);
}
}
var sampleArray = [1, 2, 3, 4, 5, 6, 7];
var sampleArray2 = [5, 6, 7, 8, 9, 10 ,11];
var similarElements =[];
for (let i = 0; i < sampleArray.length; i++) {
for (let j = 0; j < sampleArray2.length; j++) {
if (sampleArray[i] === sampleArray2[j]) {
similarElements.push(sampleArray[i]);
}
}
}
console.log(similarElements);
I have an ordered array like the following:
const arrayToSplit = [1, 3, 5, 8, 10, 12, 21, 23];
which I want to be split into multiple arrays where the difference between one and another is max a value, let us say 2:
const result = [
[1, 3, 5],
[8, 10, 12],
[21, 23]
];
or 8:
const result = [
[1, 3, 5, 8, 10, 12],
[21, 23]
];
and so forth. I have a solution but is far away from an elegant one, where I run the array by using an accumulator variable. Is there a neater, more elegant solution?
A possible solution to this:
function splitArray(arrayToSplit = []){
const explodedArray = [];
let elementsNewArray = [];
for(const element of arrayToSplit) {
if(elementsNewArray.length == 0) {
elementsNewArray.push(element);
continue;
}
if(element - _.last(elementsNewArray)) <= 2) {
elementsNewArray.push(element);
} else {
explodedArray.push(elementsNewArray);
elementsNewArray = [element];
}
}
explodedArray.push(elementsNewArray);
return explodedArray;
}
It seems reasonably straightforward to simply keep track of the last item iterated over in a variable. When iterating, check if the difference between that and the current item being iterated is larger than the limit. If it is, push a new array. Regardless. push the item being iterated over to the last array in the collection.
const arrayToSplit = [1, 3, 5, 8, 10, 12, 21, 23];
const maxDiff = 2;
const result = [[arrayToSplit[0]]];
let last = arrayToSplit[0];
for (const item of arrayToSplit.slice(1)) {
if (item - last > maxDiff) result.push([]);
result[result.length - 1].push(item);
last = item;
}
console.log(result);
This question already has answers here:
Reverse array in Javascript without mutating original array
(15 answers)
Closed 2 years ago.
I have been participating in some javaScript challenges and solved the reverse array challenge without modifying the original using the spread operator. I enjoy solving problems in different ways so i'm curious to find out from you. In what other way would you have solved it or would you solve it (excluding high order functions like map etc) ?
var newArray = [1,2,3,4,5,6];
const reverseArray = () => {
let arr = [...newArray];
for(let i = 0; i <= arr.length; i++){
arr.pop(i)
arr.unshift(i);
}
return arr
}
console.log(reverseArray())
You can use reverse();
var newArray = [1, 2, 3, 4, 5, 6];
var reverse = newArray.reverse();
console.log(reverse)
Use a for loop with increment to set index and then decrement value and push into array
var myArray = [1, 2, 3, 4, 5, 6, 7, 8];
function reverseArray(myArray) { // create a function and pass our array into it
var newArray = []; // define an empty array
for (var i = myArray.length - 1; i >= 0; i--) { // set for loop, declare a decrement for index as i - 1 to adjust for index, if greater than or equal to 0, decrement i
newArray.push(myArray[i]); // push the value into newArray
}
return newArray; // return newArray
}
console.log(reverseArray(myArray));
Use slice() reverse() and map() together index and value through function.
var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var div = document.getElementById('div')
function sliceMap() {
reverseArray = myArray.slice(0).reverse().map(
function(value) {
return value;
}
);
div.innerHTML = reverseArray;
}
console.log(sliceMap())
<div id="div"></div>
Mapping values and then using unshift to reverse them.
var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var reverseArray = [];
myArray.map((value) => {
reverseArray.unshift(value);
});
console.log(reverseArray)
Today i'm facing a really weird problem.
I'm actually trying to delete numbers below a certain number in an array.
I have this array [1, 7, 2, 3, 90, 4, 70, 20] and I only want the numbers greater than 20 !
So I should have that in output : [90, 70]
But Instead I have this array : [7, 3, 90, 70, 20] ???
Here is my code :
function superior() {
var arr = [1, 7, 2, 3, 90, 4, 70, 20]
for (var i = 0; i < arr.length; i++) {
if (arr[i] < 20) {
arr.splice(arr.indexOf(arr[i]), 1);
} else {
break;
}
}
return arr;
}
console.log(superior());
Mutating an array while you're looping through it is always going to be tricky. If you shrink the size of the array, but don't change i, then you're can end up interacting with the wrong element of the array the next time through the loop. Also, using break will stop the loop from running entirely, and so skip the rest of the array. You may have meant to use continue, but since you're on the last line of the loop anyway, continue isn't needed.
Rather than trying to change the array and loop through it at the same time, i'd recommend creating a new array. Then you can loop through the old one unhindered:
const arr = [1, 7, 2, 3, 90, 4, 70, 20]
const newArr = []
for (const i = 0; i < arr.length; i++) {
if (arr[i] >= 20) {
newArr.push(arr[i]);
}
}
console.log(newArr)
Filtering an array like this is a very common thing to do, so there are built in tools to do it for you. Every array has a .filter method. You pass into it a function describing what elements you want to keep, and it will produce the new array for you:
const arr = [1, 7, 2, 3, 90, 4, 70, 20]
const newArr = arr.filter(element => element >= 20);
console.log(newArr)
You can filter them out according to a condition.
And replace your existing array with the filtered one. Or if you don't want to replace it, use another variable and assign the filtered value to that variable.
var newArray = array.filter(item => item > 20)
Check .filter()
var array = [1, 7, 2, 3, 90, 4, 70, 20];
array = array.filter(item => item > 20)
console.log(array)
You can use Array.filter()
var arr = [1, 7, 2, 3, 90, 4, 70, 20]
var filteredArr = arr.filter(item => item > 20);
console.log(filteredArr);
You could iterate from the end and omit indexOf, because you have already the index i.
This appoach loops from the end and after splicing, the remaining lower indices remains.
function superior() {
var array = [1, 7, 2, 3, 90, 4, 70, 20],
i = array.length;
while (i--) if (array[i] < 20) array.splice(i, 1);
return array;
}
console.log(superior());
Use temporary array to push new values.
function superior() {
var arr = [1, 7, 2, 3, 90, 4, 70, 20];
temp_arr = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] > 20) {
temp_arr.push(arr[i]);
}
}
return temp_arr;
}
console.log(superior());
I would like to know how to compare two or more -- potentially unlimited -- arrays for common values and push these values into a new array efficiently. Below I have a function that will accept unlimited arguments, but I am uncertain if this is a good place to begin. PHP appears to have a method that can do what I want called array_intersect. Does javascript offer something similar?
Note: I have found examples of how this can be done with two or so arrays, but I have not found examples of how such approaches might be applied to an unspecified number of arrays as of yet. Therefore I do not see this as a duplicate question.
To further clarify, the arrays might be filled with anything. Letters, numbers, symbols, words, you name it, it might be there.
var sampleOne = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var sampleTwo = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18];
function FindDirectRelation() {
for(var i = 0; i < arguments.length; ++i) {
console.log(arguments[i]);
};
};
var directRelation = FindDirectRelation(sampleOne, sampleTwo);
I am still a coding novice, so please ensure that everything is explained in a way that is simple enough for me to understand.
using an existing intersect that works with 2 arrays, we can chain together a common sub-set using the built-in reduce() method on an array of arrays that need intersected:
function intersect(a, b) {
var aa = {};
a.forEach(function(v) { aa[v]=1; });
return b.filter(function(v) { return v in aa; });
}
var r1=[1,2,3],
r2=[1,3,4,5],
r3=[5,1,3];
alert([r1, r2, r3].reduce(intersect)) // shows: 1,3
if you define "intersect" as just being in more than one array (not every), then it's more complex...
Check to make sure the elements in the first array are also in the remaining arrays:
function multi_intersect(a) {
var other_arrays = Array.prototype.slice.call(arguments, 1);
return a . filter(function(elt) {
return other_arrays.every(function(an) {
return an.indexOf(elt) !== -1;
});
});
}
Try using Array.prototype.filter() , Array.prototype.indexOf()
var res = sampleOne.filter(function(val) {return sampleTwo.indexOf(val) !== -1})
var sampleOne = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var sampleTwo = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18];
var arr = ["a", "b", "c"];
var arr1 = ["c", "d", "e"];
var arr2 = [2, 7];
function samples() {
var args = Array.prototype.slice.call(arguments);
var res = [];
for (var i = 0, curr, next; i < args.length; i++) {
if (args[i + 1]) {
// set `curr` to array `i`
curr = args[i];
// set `next` to array `i + 1` if it exists
next = args[i + 1]
} else {
// if at last index, set `curr` to `args` : input arrays
// flattened to single array , with element at `i` removed
curr = [].concat.apply([], args.slice(0, args.length - 1));
console.log(curr)
// set next to current index
next = args[i];
};
next = next.filter(function(val) {
return curr.indexOf(val) !== -1
// filter duplicate entries at `res`
&& res.indexOf(val) === -1
});
res = res.concat.apply(res, next);
};
return res
}
var sample = samples(sampleOne, sampleTwo, arr, arr1, arr2);
console.log(sample); // [5, 6, 7, 8, 9, 10, 11, 12, "c", 2]