When i loop through the array using the splice method, the page just freezes. It looks like i caused an infinite loop. lib.randomInt() works, so that is not the problem.
function() {
return function(string) {
var arr = string.split("")
arr.sort();
for(var i = 0; arr.length;i++){
arr.splice((i+1),0,lib.randomInt(9));
}
var pseudocryptarr = arr.join("");
}
})()("example");
This is from a different file that is placed above the main file in html
var lib = {
factorial: function(num){
function _factorial(num){
if(num === 1){
return 1;
} else {
return num*_factorial(num-1);
}
}
console.log(num+"! = " + _factorial(num));
},
randomInt: function(int,offset){
if(offset == undefined || null || NaN){
offset = 0;
}
return Math.floor(Math.random()*int)+offset;
},
display: function(m, fn){
fn(m);
}
};
You've got to loop in reverse when modifying the array itself to avoid corrupting the loop like this...
for (var i=arr.length-1; i>=0; i--){}
I guess that you wanted to insert a random value after every array element, so that the string "example" would become something like "e5x9a2m4p7l1e3"
There are two issues:
Your for loop has no end condition that will become false. You need to state i < arr.length instead of just arr.length which is always truthy for non-empty arrays.
You add array elements in every iteration, but then also visit them in the next iteration, and from there on you will only be visiting the new inserted values and never get to the next original element that keeps being 1 index away from i. You need to increment i once more. For that you can use ++i instead if i+1 as the splice argument.
So your loop should be:
for(var i = 0; i < arr.length; i++) {
arr.splice(++i,0,lib.randomInt(9));
}
const lib = { randomInt: n => Math.floor(Math.random()*n) };
(function() {
return function(string) {
var arr = string.split("")
arr.sort();
for(var i = 0; i < arr.length; i++) {
arr.splice(++i,0,lib.randomInt(9));
}
var pseudocryptarr = arr.join("");
console.log(pseudocryptarr);
}
})()("example");
Or to save an addition:
for(var i = 1; i <= arr.length; i+=2) {
arr.splice(i,0,lib.randomInt(9));
}
const lib = { randomInt: n => Math.floor(Math.random()*n) };
(function() {
return function(string) {
var arr = string.split("")
arr.sort();
for(var i = 1; i <= arr.length; i+=2) {
arr.splice(i,0,lib.randomInt(9));
}
var pseudocryptarr = arr.join("");
console.log(pseudocryptarr);
}
})()("example");
I fixed it. I wanted after each character for there to be a number. Using the pre-looped array length and doubling it while iterating twice, means that the splice adds the number after the new number element and then the character.
Edit: My typo was the problem. I didnt even have to use len, just iterate by 2.
for(var i = 0;i < arr.length;i+=2){
arr.splice((i+1),0,lib.randomInt(9));
}
(function() {
return function(string) {
var arr = string.split("")
arr.sort();
var len = arr.length
for(var i = 0;i < len*2;i+=2){
arr.splice((i+1),0,lib.randomInt(9));
}
var pseudocryptarr = arr.join("");
console.log(pseudocryptarr);
}
})()("example");
Edit: user4723924 method is better:
(function() {
return function(string) {
var arr = string.split("")
arr.sort();
for(var i = arr.length;i >= 0;i--){
arr.splice((i+1),0,lib.randomInt(9));
}
var pseudocryptarr = arr.join("");
console.log(pseudocryptarr);
}
})()("example");
I just don't understand why does this function return an empty array instead of newArr = [1, 2, 3, etc.] depending on the length of the array.
function randomFunction(num) {
var newArr = [];
for(var i = 1; i < num.length; i++) {
newArr.push(i);
}
return newArr;
};
If num is supposed to be the length of the new array, and the last number of the range of values, you have to use it directly, instead of using length (which is meant to be used for an array):
function randomFunction(num) {
var newArr = [];
for(var i = 1; i <= num; i++) {
newArr.push(i);
}
return newArr;
};
var array = randomFunction(5);
console.log(array);
Also, you might want use <= instead of <, in case you want to start the value by 1 and go through n, and not n - 1.
function randomFunction(num) {
var newArr = [];
for(var i = 1; i < num /* number has no length */; i++) {
newArr.push(i);
}
return newArr;
};
Es6 alternative for fun:
return new Array(num).fill().map((r, i) => i)
randomFunction(8) ; for example
A number doesn't have length at all. It's already a value.
You do not need length attribute at all. just
for(var i = 1; i < num; i++) {
newArr.push(i);
}
function randomFunction(num) {
var newArr = [];
for (var i = 1; i < num; i++) {
newArr.push(i);
}
return newArr;
};
console.log(randomFunction(8))
num is already a number. You don't need use .lenght property
function randomFunction(num) {
var newArr = [];
for(var i = 1; i <= num; i++) {
newArr.push(i);
}
return newArr;
};
randomFunction(5); // [ 1, 2, 3, 4, 5 ]
This is one of freecodecamps challenges it passes the for loop inside the filter passes the first element of the array newArg but doesn't for the second one and so on therefore the challenge doesn't pass can someone explain to me why. Please don't write any full solutions as i just want a little help to move forward.
function destroyer(arr) {
// Remove all the values
var newArg = [];
for (var i=1; i < arguments.length; i++){
newArg.push(arguments[i]);
}
var newArray = arr.filter(function(val){
for (i = 0; i < newArg.length; i++) {
return val !== newArg[i];
}
});
return newArray;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
The filter call:
var newArray = arr.filter(function(val){
for (i = 0; i < newArg.length; i++) {
return val !== newArg[i];
}
});
is the same as:
var newArray = arr.filter(function(val) {
return val !== newArg[0];
});
because you are returning from the very first iteration.
Solution:
You'll have to wrap the return statement in an if like this:
var newArray = arr.filter(function(val){
for (i = 0; i < newArg.length; i++) {
if(val === newArg[i]) { // don't return if val !== newArg[i]
return true; // return only when they're ===
}
}
return false; // default return (nothing is found in the array)
});
Or use an alternative such as Array.prototype.some like this:
var newArray = arr.filter(function(val){
return newArg.some(function(arg) { // return true if some item pass the test (false otherwise)
return arg === val; // the test
})
});
I have a function urlScores which return an array of object in the form
[{"url":"facebook","score":2},{"url":"reddit","score":1},{"url":"stackoverflow","score":3}]
I am asked to sort this array in regards to its score using bubble sort.
What I have tried doing is creating a bubble sorting function that takes the object returned from urlScores and sorts it.
function sort(object)
{
for(var i= 0; i < object.length; i++){
if (object[i].score > object[i+1].score) {
var temp = object[i]
object[i]=object[i+1]
object[i+1]=temp
}
}
}
And the function that should be called for sorting the array looks like:
function rankedScores(web,pattern)
{
return (sort(urlScores(web,pattern)))
}
This doesn't seem to be working, I am faced with TypeError: object[(i + 1)] is undefined
Any help is appreciated
I have corrected your sort function.
function sort(a) {
for (var i = 0; i < a.length - 1; i++) {
if (a[i].score > a[i + 1].score) {
var temp = a[i]
a[i] = a[i + 1]
a[i + 1] = temp
}
}
return a;
}
Here is an example
var arr= '[{"url":"facebook","score":2},{"url":"reddit","score":1},{"url":"stackoverflow","score":3}]';
console.log(sort(arr));
var a = [{"url":"facebook","score":2},{"url":"reddit","score":1},{"url":"stackoverflow","score":3}];
function bubbleSort(a)
{
var swapped;
do {
swapped = false;
for (var i=0; i < a.length-1; i++) {
if (a[i].score > a[i+1].score) {
var temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
swapped = true;
}
}
} while (swapped);
}
bubbleSort(a);
console.log(a);
Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.
For example:
moveZeros([false,1,0,1,2,0,1,3,"a"]) // returns[false,1,1,2,1,3,"a",0,0]
My code:
var moveZeros = function (arr) {
var zeros = [];
var others = [];
var res;
var arrayLength = arr.length;
for (var i = 0; i < arrayLength; i++) {
if (arr[i] == 0) {
zeros.push(arr[i]);
} else {
others.push(arr[i]);
}
}
var res = others.concat( zeros );
return res;
}
I get the following result:
Expected: ["a","b",null,"c","d",1,false,1,3,[],1,9,{},9,0,0,0,0,0,0,0,0,0,0],
Instead got: ["a","b",null,"c","d",1,1,3,1,9,{},9,0,0,0,false,0,0,[],0,0,0,0,0]
The expected result is quite close to what I achieved (see above) . I don't understand why I have false in a different place?
try this simply
var arr = [false,1,0,1,2,0,1,3,"a"];
arr.sort(function(a,b){if (a===0){return 1}});
document.body.innerHTML += JSON.stringify(arr);
Try to use a normal for loop and splice at this context to make your job done,
var arr = [false,1,0,1,2,0,1,3,"a"];
for(var i=arr.length;i>0;i--){
if(arr[i] === 0){ arr.push(arr.splice(i,1).pop()); }
}
console.log(arr); //[false, 1, 1, 2, 1, 3, "a", 0, 0]
document.body.innerHTML += JSON.stringify(arr);
Use Array#splice() and Array#push().
function moveZeros(a) {
var i = a.length - 1;
while (i--) {
if (a[i] === 0) {
a.push(a.splice(i, 1)[0]);
}
}
return a;
};
var array = [false, 1, 0, 1, 2, 0, 1, 3, "a"];
document.write('<pre>' + JSON.stringify(moveZeros(array), 0, 4) + '</pre>');
Another approach with swapping items.
function moveZeros(array) {
var length = array.length,
i = length;
while (--i) {
if (array[i] !== 0) continue;
length--;
while (i < length) {
[array[i + 1], array[i]] = [array[i], array[i + 1]];
i++;
}
}
return array;
}
var array = [false, 1, 0, 1, 2, 0, 1, 3, "a"];
console.log(...moveZeros(array));
Please use === operator to compare if value is 0:
if (arr[i] === 0) {
zeros.push(arr[i]);
} else {
others.push(arr[i]);
}
The code snippet below should work , please try , reason for null is that the length of the arr starts count from zero so when using <= you should subtract 1 from the total length.
var moveZeros = function (arr) {
// TODO: Program me
let zero = []
let others = []
let together = []
for (let i =0; i <= arr.length-1; i++){
if (arr[i] === 0){
zero.push(arr[i])
}
else{
others.push(arr[i])
}
}
together = others.concat(zero)
return together
}
var titleCase = function(title) {
var arr = [];
for (i = 0; i < title.length ; i++) {
if (title[i] !== 0 ) {
arr.push(title[i]);
}
}
for (i = 0 ; i < title.length ; i++) {
if (title[i] == 0 ) {
arr.push(title[i]);
}
}
return arr;
}
You could use the filter() method to achieve your goal. With the arrow notation you can shorten the code. For example: arr => arr === 0 is the shorthand for the anonymous filter function function(arr) { return arr === 0; }
var moveZeros = function (arr) {
const zeros = arr.filter (arr => arr === 0);
const others = arr.filter (arr => arr !== 0);
return others.concat(zeros);
}
var arr = [false,1,0,1,2,0,1,3,"a"]
function moveZeros(arr){
var zeros = [];
var others = [];
var output;
for (var i=0; i< arr.length; i++){
if (arr[i]===0){
zeros.push(arr[i]);
}else{
others.push(arr[i])
}
}
output = others.concat(zeros);
console.log(output);
}
moveZeros([false,1,0,1,2,0,1,3,"a"]);