How to assign element of looping array to another in JS? - javascript

...
function ar(farray) {
var array = farray.slice(0, 2);
for (i = 2; i <= farray.length; i++) {
if (array[0] < farray[i]) {
//Here is the problem.Why i can 't just (re)assign value, referencing to another array?
//need to be assigned-copied-rewrited!!
array[0] = farray[i];
}
}
return array[0] + array[1];
}
Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 integers. No floats or empty arrays will be passed.
function sumTwoSmallestNumbers(numbers) {
var array=numbers.slice(0,2);
array.sort(function(a,b){return b-a});
array[0]=numbers[0];
array[1]=numbers[1];
for (i=2;i<=numbers.length; i++){
if (numbers[i]<array[0] || numbers[i]<array[1]) {
if (numbers[i]<array[0]) {
array[0]=numbers[i];
} else {
array[1]=numbers[i];
}
}
Solved!
//My sorting relies on positions of value in 'array', therefore for every 'for' loop I need prepared positions
array.sort(function(a,b){return b-a});
}
return array[0]+array[1];
};

why you need another array ?
function ar(farray) {
var a = farray[0];
for (i = 2; i <= farray.length; i++) {
if (a < farray[i])
a = farray[i];
}
return a + farray[1];
}

Related

How to add a string to an array and return the string

Build a function forLoop. It takes an array as an argument. Start counting from 0, and, using a for loop, add a string to the array 25 times. But not just any string. If your i value is 1, add the string "I am 1 strange loop."; if your i value is anything else, add the string "I am ${i} strange loops.". (Remember flow control with if and else? And how do we interpolate i?) Then return the array.
Learning online and am having trouble understanding what is needed to return the array with the string added to it 25 times?
function forLoop(array) {
for (let i = 0; i < 25; i++) {
if (i === 1) {
console.log(`${array} I am 1 strange loop.`);
} else {
console.log(`${array}I am ${i} strange loops.`);
}
}
}
forLoop(array);
adds `"I am ${i} strange loop${i === 0 ? '' : 's'}."` to an array 25 times:
TypeError: Cannot read property 'slice' of undefined
You're close. You simply need to push the string to the array, and then return the array at the end.
function forLoop(arr) {
for (let i = 0; i < 25; i++) {
if (i === 1) {
// Use `push` to add the string to the array
arr.push(`I am 1 strange loop.`);
} else {
arr.push(`I am ${i} strange loops.`);
}
}
// Return your array
return arr;
}
// Create the array and pass it into the function
const arr = [];
// `out` captures the returned array
const out = forLoop(arr);
console.log(out);
You were almost there. Small updates done and posted below
function forLoop(array) {
for (let i = 1; i <= 25; i++) {
array.push(`I am ${i} strange ${i == 1 ? 'loop' : 'loops'}.`)
}
return array;
}
const result = forLoop([]);
console.log(result);
function forLoop(array: string[]) {
for (let i = 0; i < 25; i++) {
var messsage= 'I am '+i+' strange loop' + (i>0 ? 's.':'.');
array.push (messsage);
console.log(array[i])
}
}
const array:string[]=[];
forLoop(array);
console.log(array.length)
jsfiddle Link

JavaScript - for Loop vs. Array shift

I have two functions, they do look alike but what I don't really understand is when inside the for-loop, since the input is an array, why doesn't the array need any index to call the first array?
I have an array of...
var puzzlers = [
function(a) { return 8 * a - 10; },
function(a) { return (a - 3) * (a - 3) * (a - 3); },
function(a) { return a * a + 4; },
function(a) { return a % 5; }
];
I'm trying to loop through the array with an input. The result of the first function will then be used as the next function's input then the first array will be removed.
This is what I wrote...
function applyAndEmpty(input, queue)
{
var length = queue.length;
for(var i = 0; i < length; i++)
{
input = queue[0](input);
queue.shift();
}
return input;
}
The above does give me the answer but then I see that there's another way of writing it which is
var applyAndEmpty = function(input, queue)
{
var length = queue.length;
for(var i = 0; i < length; i++)
{
input = queue.shift()(input);
}
return input;
};
What I don't understand is the part input = queue.shift()(input).
Doesn't the queue need an index?
So you're basically asking what shift does and here you go:
What you can do using for(var i=0;... you can do using shift() (quite similar but not!)
Using for loop (and index)
var array = [
function(){return "a";},
function(){return "b";}
];
for(var i=0; i<array.length; i++){
console.log( array[i]() );
// "a"
// "b"
}
console.log(array.length); //2 !!Still there!!!
Using shift() (and while for example)
var array = [
function(){return "a";},
function(){return "b";}
];
while(array.length){ // while array has length
console.log( array.shift()() ); // execute and remove from array
// "a"
// "b"
}
console.log(array.length); //0 !!!Empty array due to shift()!!!
So basically it removes a key from your Array and returns it.
As long as that array has keys it will loop until it's empty.
The difference between the two is drastic:
The for loop in example 1. will loop but not alter your original array.
Using shift() in example 2. you're (using and) removing your Array keys one by one.
Read more about Array manipulation:
Array.prototype.shift 1 <-- [2,3,4]
Array.prototype.unshift 5 --> [5,2,3,4]
Array.prototype.push [5,2,3,4,6] <-- 6
Array.prototype.pop [5,2,3,4] --> 6
and other Methods
You can simplify the logic using Array.reduce
Here how you can do that:
var puzzlers = [
function(a) { return 8 * a - 10; },
function(a) { return (a - 3) * (a - 3) * (a - 3); },
function(a) { return a * a + 4; },
function(a) { return a % 5; }
];
function runPuzzler(inputValue){
return puzzlers.reduce(function(prev, curr){
return curr(prev);
},inputValue);
}
Output :
EachArrayValues::100
EachArrayValues::200
EachArrayValues::0
EachArrayValues::400
EachArrayValues::500
EachArrayValues::-50
Negative value found, ie -50

Javascript: Write a function that takes in an array, and then returns an array with only unique numbers, only arrays removed

Write a function that takes in a list and returns a list with all of the duplicates removed (list will only have unique numbers).
Here's what I have so far:
var lista = [1,4,5,1,1,3,5,6,4,4,3];
function dupRemove (lista) {
//Sort the array in case it isn't sorted
lista.sort();
//Object to store duplicates and unique numbers
var listNumbers = {
"Duplicate Numbers": [],
"Unique Numbers": []
};
for (var i = 0; i < lista.length; i++) {
//check if it is not equal to the index of the array before it and after. if it isn't, that means its unique, push it in the uniques array.
if (lista[i] !== lista[i-1] && lista[i] !== lista[i+1]) {
listNumbers["Unique Numbers"].push(lista[i]);
} else {
listNumbers["Duplicate Numbers"].push(lista[i]);
}
}
return listNumbers;
}
Currently, my solution returns an object with keys with the values of "Duplicates": 1, 1, 1, 3, 3, 4, 4, 4, 5, 5 and "Uniques": 6.
How do I remove the duplicates from duplicates and then join these two keys into a single array?
Thank you.
that answer is seriously over -engineered- all you need to to is push all values into a new array if they are not already in it.
function=removeDups()
{
var lista = [1,4,5,1,1,3,5,6,4,4,3];
var uniqueValues=[];
var duplicateValues=[];
for(i=0;i<lista.length;i++)
{
if(uniqueValues.indexof(lista[i] == -1){uniqueValues.push(lista[i]}else{duplicateValues.push(lista[i]}
}
}
You could just use the default filter method that is on all Arrays
You don't need the sort function either. If the item is already found using the indexOf method it will not be added to the newly returned array created by the filter method
var list = [1,4,5,1,1,3,5,6,4,4,3];
function removeDup (arr) {
return arr.filter(function(item, pos) {
return arr.indexOf(item) == pos;
})
}
var sortedList = removeDup(list).sort(function(a,b){
return a - b
})
document.getElementsByTagName('div')[0].textContent = sortedList
<div></div>
Kind of a non elegant solution but it gives you the two arrays: one with the duplicate values and one with the unique ones. Since you cannot rely on .sort() you can just count things.
Function checkList will give you back those two arrays.
var list = [1,4,5,1,1,3,5,6,4,4,3];
console.log(checkList(list));
function checkList(list) {
var uniques = []; // will be [6]
var dups = []; // will be [1, 4, 5, 3]
var checked = []; // save what you have already checked so far
for(i = 0; i < list.length; i++) {
if(notChecked(list[i], checked)) {
checked.push(list[i]);
if(count(list[i], list) > 1) {
dups.push(list[i]);
} else {
uniques.push(list[i]);
}
}
}
return {dups: dups, uniques: uniques}
}
// count how many num in arr
function count(num, arr) {
var count = 0;
var i;
for(i = 0; i < arr.length; i++) {
if(arr[i] == num) count++;
if(count > 1) return count;
}
return count;
}
// check if num has not been checked
function notChecked(num, arr) {
return (arr.indexOf(num) == -1) ? true : false;
}

Deleting Element After Pushing

If I have an array where I am pushing certain elements to a second array- how can I delete those elements from the first array after pushing them to the second? Here is sample code:
for(var a = 0; a < arr.length; a+=1){
if(arr[a].length == 4){
other.push(arr[a]);
}
}
In other words, I know longer want elements arr[a] to be in arr if they have been pushed to other.
Just do a splice on that original array index to remove that element if you no longer require it.
for(var a = 0; a < arr.length;){
if(arr[a].length == 4){
other.push(arr[a]);
arr.splice(a, 1);
}
else {
a += 1;
}
}
This seems fine:
for(var a = 0, length=arr.length; a < length; a++){
if(arr[a].length == 4){
other.push(arr[a]);
arr.splice(a,1);
}
}
Write a function which takes an input array, and a function to determine if an element should be moved. It returns a two-element array, containing the modified input, and the new array into which elements have been extracted.
function extractIf(array, condition) {
return [
array.filter(not(condition)),
array.filter( condition)
];
}
// Specify which elements are to be extracted/moved.
function condition(elt) { return elt.length === 4; }
// Little helper function to invert a function.
function not(fn) { return function() { return !fn.apply(this, arguments); }; }
Invoke this as:
var results = extractIf(arr, condition);
arr = results[0];
other = results[1];
underscore solution
If you are willing to use underscore, you could group the input by the true/false value of the condition:
var groups = _.groupBy(arr, function(elt) { return elt.length === 4; })
Your original array with the elements removed will be in groups.false, and the other array in groups.true.

Are there such things as dynamic-dimensional arrays in JavaScript?

What I mean by dynamic-dimensional arrays is multidimensional arrays that can have various dimensions. I need to create a function that does something to elements of multidimensional arrays, regardless of their dimensions. I wrote a function that should loop through all elements of a multidimensional array, but I can't find a way to get them. Here's what I wrote:
function loopThrough (multiArray, dimensions) {
var i, indexes = new Array(dimensions.length);
// stores the current position in multiArray as index combination
for (i in indexes) indexes[i] = 0; // position is initialised with [0, 0, ... 0]
while (i >= 0) {
doStuff(multiArray[indexes[0], indexes[1], ... indexes[?]]); // this is where I got stuck
for (i = indexes.length - 1; i >= 0 && ++indexes[i] >= dimensions[i]; indexes[i--] = 0);
// creates the next index combination
}
}
I also need a way to create such arrays. Say in an object's constructor, like:
function MultiArray (dimensions) {
this.array = [];
// create multidimensional array
}
For example, if I want to create a 5x3x8 array I should be able to call MultiArray([5,3,8]); just the same as calling MultiArray([4,6]); for a 4x6 array, or MultiArray([7]); for a plain 7-lengthed array.
You can use something like this:
function MultiArray(dimensions) {
var a = [];
if (dimensions > 1) {
a.push(MultiArray(dimensions -1));
}
return a;
}
var m = MultiArray(4);
function MultiArray(dimensions) {
this.elements = [];
var leaf = dimensions.length == 1;
var dimension = dimensions.shift();
for (var i = 0; i < dimension; ++i) {
this.elements.push(leaf ? undefined : new MultiArray(dimensions));
}
}
MultiArray.prototype.get(indexes) {
var leaf = indexes.length == 1;
var index = indexes.shift();
return leaf ? this.elements[index] : this.elements[index].get(indexes);
}
MultiArray.prototype.set(indexes, value) {
var leaf = indexes.length == 1;
var index = indexes.shift();
if (leaf) {
this.elements[index] = value;
} else {
this.elements[index].set(indexes, value);
}
return this;
}
var m = new MultiArray([4, 3, 5]);
m.set([1, 2, 4], "i'm a value in a multi dimensional array");
m.get([1, 2, 4]); // should return "i'm a value in a multi dimensional array"
m.get([2, 0, 3]); // should return undefined
m.get([0, 1]); // should return an array of 5 elements

Categories

Resources