Related
// sorting an array
const least_num = (arr)=>{
let smallest = arr[0];
let smallest_index = 0;
for(let i=1; i<arr.length;i++){
if (arr[i] < smallest) {
smallest = arr[i];
smallest_index = i;
}
}
return smallest_index
}
const sortArray = (arr)=>{
const newArr = [];
for(let i in arr){
let smallest = least_num(arr);
console.log(smallest,i)
console.log(arr.splice(smallest,1),arr)
}
return newArr;
}
console.log(sortArray([5,4,3,2,1]));
I am trying to sort array without sort().
It stuck at array length of 2.
It may because of for loop. And how to remove element in a array using index.
A few issues:
The code never adds anything to newArr, so the function always returns an empty array. It should add the removed (spliced) element to newArr. This can be done with newArr.push(...arr.splice(smallest,1))
The for..in loop will iterate fewer times than expected, because in each iteration the array gets shorter, thereby removing future iterations for the loop. As the idea is to remove all items from the array, just keep looping until the array is empty with while (arr.length)
With these two corrections, your code works:
const least_num = (arr)=>{
let smallest = arr[0];
let smallest_index = 0;
for(let i=1; i<arr.length;i++){
if (arr[i] < smallest) {
smallest = arr[i];
smallest_index = i;
}
}
return smallest_index
}
const sortArray = (arr)=>{
const newArr = [];
while(arr.length) {
let smallest = least_num(arr);
console.log(smallest)
newArr.push(...arr.splice(smallest,1));
console.log(arr)
}
return newArr;
}
console.log(sortArray([5,4,3,2,1]));
You can also try this.
const sortArray = (arr)=>{
let originalArr = [...arr];
var sortArr = [];
while(originalArr.length) {
let val = originalArr[0];
for ( let j = 1; j < originalArr.length; j++ ) {
if(val>originalArr[j]) {
val = originalArr[j];
}
}
sortArr.push(originalArr.splice(originalArr.indexOf(val), 1)[0]);
}
return sortArr;
}
console.log(sortArray([5,4,3,2,1]));
I would like to compare two array then return the index once first array less than second array. But if the start value of first array greater than the second array, must skip until first array value less than second array. For example
case1: This must return index = 2 (exampleArr1 < exampleArr2 at index =2)
var exampleArr1 = [15,9,7,5,3,1];
var exampleArr2 = [2,6,8,12,17,22];
function compareArray(exampleArr1,exampleArr2){
...
return result
}
case2: This must return index = 6 (exampleArr1 < exampleArr2 at index =6)
var exampleArr1 = [1,2,4,5,15,9,7,5,3];
var exampleArr2 = [2,3,5,6,2,6,8,12,17];
function compareArray(exampleArr1,exampleArr2){
...
return result
}
Any advice or guidance on this would be greatly appreciated, Thanks.
A simple for loop will suffice. In our loop, we already have the index so we just compare the first array at this index with the second array at this index.
const compareArray = (arr1, arr2) => {
let startIndex = 0
if (arr1[0] < arr2[0]) {
// find the index from arr1 that is greater than arr2
startIndex = arr1.findIndex((a, index) => a > arr2[index])
}
for (let i = startIndex; i < arr1.length; i++) {
if (arr1[i] < arr2[i]) {
return i
}
}
}
const exampleArr1 = [15,9,7,5,3,1]
const exampleArr2 = [2,6,8,12,17,22]
const exampleArr3 = [1,2,4,5,15,9,7,5,3]
const exampleArr4 = [2,3,5,6,2,6,8,12,17]
console.log(compareArray(exampleArr1, exampleArr2))
console.log(compareArray(exampleArr3, exampleArr4))
Please use the findIndex method in your function like
var exampleArr1 = [15,9,7,5,3,1];
var exampleArr2 = [2,6,8,12,17,22];
function compareArray(exampleArr1,exampleArr2) {
if (exampleArr1[0] < exampleArr2[0]) {
exampleArr1 = exampleArr1.slice(1);
}
return exampleArr1.findIndex(function(e, i) { return exampleArr2[i] > e; });
}
console.log(compareArray(exampleArr1, exampleArr2));
I have a function which creates an array of subarrays. It takes three parameters: the number of subarries to create within the array (numSub), the number of times the desired value occurs within each subarray (numValue), and the desired value (value).
For example, if I were to call the function with (3, 2, test), I would want the following output:
Array [Array ["test", "test"], Array ["test", "test"], Array ["test", "test"]]
Here is the function I have written:
function subarrs(numSub, numValue, value) {
let arr = [];
for (let i = 0; i < numSub; i++) {
arr.push([]);
}
arr.forEach(function(sub) {
sub.fill(value, 0, numValue - 1);
});
return arr;
}
console.log(subarrs(3, 2, 'test'));
I have looped through the numSub variable and inserted an array into arr for each iteration. This was successful. (Array [Array [], Array [], Array []])
I then use a forEach loop to fill each sub-array with value beginning at index 0 and ending at index numValue - 1 (because the second occurrence of the value would actually be at index 1.)
The function does not work as intended, however. Rather than the aforementioned desired output, I receive this:
Array [Array [], Array [], Array []]
You can use fill on an array that has received the right length, like Array(numValue).fill(numValue). Here is how you could do it:
function subarrs(numSub, numValue, value) {
return Array.from({length: numSub}, () => Array(numValue).fill(value));
}
console.log(subarrs(3, 2, 'test'));
You are filling an empty array. It's still an empty array (nothing to fill).
You should construct the array of some length:
arr.push(new Array(numValue));
Complete:
function subarrs(numSub, numValue, value) {
let arr = [];
for (let i = 0; i < numSub; i++) {
arr.push(new Array(numValue));
}
arr.forEach(function(sub) {
sub.fill(value);
});
return arr;
}
console.log(subarrs(3, 2, 'test'));
Array.fill() only modifies array values. It does not add new ones. Use push again instead
function subarrs(numSub, numValue, value) {
let arr = [];
for (let i = 0; i < numSub; i++) {
arr.push([]);
}
arr.forEach(function(sub) {
for (let j = 0; j < numValue; j++) {
sub.push(value);
}
});
return arr;
}
console.log(subarrs(3, 2, 'test'));
You can use .push method to add value into your array instead .fill, see working demo :
function subarrs(numSub, numValue, value) {
let arr = [];
for (let i = 0; i < numSub; i++) {
arr.push([]);
for (let j = 0; j < numValue; j++) {
arr[i].push(value);
}
}
return arr;
}
console.log(subarrs(3, 2, 'test'));
fill will only work on indexes that already exist and its second parameter in your case should be the length of the array (which is the default value) and not length - 1. You can see it here:
let myEmptyArray = [];
let myFullArray = [1, 2, 3, 4];
myEmptyArray.fill(0, 0, 4);
myFullArray.fill(0, 0, 4);
console.log(myEmptyArray, myFullArray)
You could push an Array with the necessary slots already in place with new Array(numValue). Something like this:
function subarrs(numSub, numValue, value) {
let arr = [];
for (let i = 0; i < numSub; i++) {
arr.push(new Array(numValue));
}
arr.forEach(function(sub) {
sub.fill(value);
});
return arr;
}
console.log(subarrs(3, 2, 'test'));
If you have es2015+ You can do it easily :
const subarrs = (length, subLength, value) =>
[...Array(length)].map(() => [...Array(subLength)].fill(value));
subarrs(3, 2, 'test');
(Edited) after the first comment
I'm trying to do a for loop on an array and be able to start that loop on a specific index and loop over the array x amount of times.
const array = ['c','d','e','f','g','a','b','c']
I want to loop 8 indexes starting at any index I wish. Example starting at array[4] (g) would return
'g','a','b','c','c','d','e','f'
This is what I've tried so far
const notes = ['c','d','e','f','g','a','b','c']
var res = []
for (var i = 4; i < notes.length; i++) {
res.push(notes[i])
}
console.log(res)
You can use modulo % operator.
const getArray = (array, index) => {
const result = [];
const length = array.length;
for (let i = 0; i < length; i++) {
result.push(array[(index + i) % length]);
}
return result;
};
Simple way.
var notes = ['c','d','e','f','g','a','b','c'];
function looparr(arr, start)
{
var res = [], start = start || 0;
for(var index = start, length=arr.length; index<length; index++)
{
res.push(arr[index]);
index == (arr.length-1) && (index=-1,length=start);
}
return res;
}
console.log(looparr(['c','d','e','f','g','a','b','c'], 0));
console.log(looparr(['c','d','e','f','g','a','b','c'], 2));
console.log(looparr(['c','d','e','f','g','a','b','c'], 4));
console.log(looparr(['c','d','e','f','g','a','b','c']));
Very simple solution below :)
While i < index, remove the first character from the array, store it in a variable and then add it back onto the end of the array.
let array = ['c','d','e','f','g','a','b','c'];
var index = 4;
for(var i = 0; i < index; i++) {
var letter1 = array.shift(i); // Remove from the start of the array
array.push(letter1); // Add the value to the end of the array
}
console.log(array);
Enjoy :)
I have a array like this:
var oldArr = [2,3,4,2,3,5,6,4,2,3,2];
var newArr = [];
I am passing a argument(number) to a function which should insert values from oldArr into newArr taking the argument as length for each element found in old array.
function getNumbers(num){
console.log('value passed is ', num);
for(var i=0; i<arr.length;i++){
newArr.push(arr[i]);
}
console.log('newArr', newArr);
}
getNumbers(2);
For example,
if I pass number 2 as in getNumbers(2);
new array output should be:
[2,2,3,3,4,4,5,5,6,6] //as the argument/length passed is 2.
if I pass number 3 as in getNumbers(3);
[2,2,2,3,3,3,4,4,4,5,5,5,6,6,6] //as the argument/length passed is 3.
How do I achieve this?
Try this
var oldArr = [2,3,4,2,3,5,6,4,2,3,2];
function getNumbers(arr, num){
return Array.from(new Set(arr))
.map((e) => new Array(num).fill().map(v => e))
.reduce((a, b) => a.concat(b),[]);
}
console.log(getNumbers(oldArr, 2));
console.log(getNumbers(oldArr, 3));
First of all, you need to get the unique values from the array. That's the Array.from(new Set(arr));.
Secondly, we can allocate new array for each number (to be able to nicely flatten it later). That's what new Array(num).fill().map(v => e)) does. Result of this will be like [[2,2],[3,3],[4,4]..] etc.
And lastly, flatten it all using Array.prototype.reduce.
var oldArr = [2,3,4,2,3,5,6,4,2,3,2];
var uniqueArr = oldArr.filter(function(elem, index, self) {
return index == self.indexOf(elem);
})
console.log(uniqueArr)
function getNumbers(num){
var newArr = [];
for(var i=0; i<uniqueArr.length;i++){
for(var j=0;j<num;j++)
newArr.push(uniqueArr[i]);
}
console.log('newArr', newArr);
}
getNumbers(2);
getNumbers(3);
Remove all your duplicates from your old array using Array#Filter , then loop through all element and store it in new array.
The following function should work
function duplicateN(oldArray, newArray, N) {
for (var i = 0; i < oldArray.length; i++) {
for (var j = 0; j < N; j++) {
newArray.push(oldArray[i]);
}
}
}
It simply iterates over each value in the original array and then inserts it N times.
I'm not sure the usage of this, but if newArray is always empty, something like this would be more maintainable
function duplicateN(inputArray, N) {
var duplicatedArray = [];
for (var i = 0; i < inputArray.length; i++) {
for (var j = 0; j < N; j++) {
duplicatedArray.push(inputArray[i]);
}
}
return duplicatedArray;
}
var arr = [2,3,4,5];
function getNumbers(num){
var j = 1;
var newArr = [];
for(var i=0; i<arr.length;i++)
{
j = 1;
while(j<=num){
newArr.push(arr[i]);
j++;
}
}
console.log(newArr.join());
}
getNumbers(4);
let multiply_array = (arr, mi = 1) =>
[].concat.apply([], arr.filter((i, ind) =>
arr.indexOf(i) == ind).map(i =>
Array(mi).fill(i)));
The multiply_array function takes two parameters, an array and the multiplying integer. It filters through the array and finds all unique values by comparing position. It then maps over all the remaining unique integers and replaces them with an array that is the length specified by the passed in multiplying integer, and filled with the unique value. All of it is concatenated together to form one array.
var oldArr = [2, 3, 4, 2, 3, 5, 6, 4, 2, 3, 2];
var newArr = [];
let multiply_array = (arr, mi = 1) =>
[].concat.apply([], arr.filter((i, ind) =>
arr.indexOf(i) == ind).map(i =>
Array(mi).fill(i)));
console.log(multiply_array(oldArr, 3));
You can do this using chain of Array.prototype methods:
var oldArr = [2,3,4,2,3,5,6,4,2,3,2];
function getNumbers(num){
return oldArr
.filter((elem, index, arr) => !arr.slice(index + 1).includes(elem))
.sort((prev, next) => next < prev)
.reduce((result, elem) => result.concat(Array(num).fill(elem)), [])
}
console.log(getNumbers(2));
console.log(getNumbers(3));