Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Is it possible to replace a numeric value in a javascript array with a string?
for example:
var a=[1,2,3,4,5]
I need to replace #3 with apple.
Is it even possible?
Use .indexOf(3) to find where 3 is in the array, and then just do a[index] = "apple"; to replace the value. I created a snipped for you below.
var a = [1, 2, 3, 4, 5];
var index = a.indexOf(3);
console.log("Before: " + a);
a[index] = "apple";
console.log("After: " + a);
Aniket G's solution works, but only replaces the first occurrence of a value.
// arr is the array we're acting on
// n is the value we want to replace
// str is the string that we want n replaced with
function replaceNumWithStringInArray(arr, n, str) {
for (let i = 0; i < arr.length; ++i) {
if (arr[i] === n) {
// we found a match, replace the former value (n) with a string (str)
arr[i] = str;
}
}
// we don't have to return anything here, because it modifies the array in place
}
var a = [1,2,3,4,5,3]; // added another 3 to illustrate that it replaces all occurences of n
console.log('before', a);
replaceNumWithStringInArray(a, 3, 'apple');
console.log('after', a);
Yes, of course it's possible! I suggest you read some documentation on javascript arrays to see just how powerful they are.
Basically, javascript arrays are high-level list objects that can be made up of many different data-types. If you would have actually tried what you were curious about before asking about it here, you would have found it to be quite simple.
var a = [1,2,3,4,5];
a[2] = "apple";
Replaces the third element of array a with "apple".
You can iterate over your array and check for the given value. Especially useful if the value occurs multiple times:
function stringifyValue(array, valueToStringify) {
for(let i = 0; i < array.length; i++) {
if(array[i] === valueToStringify){
array[i] = '' + array[i];
}
}
}
Or if you want to update a value at the given index:
const indexWithValue = 3;
array[indexWithValue] = '' + array[indexWithValue];
Related
This question already has answers here:
How to filter an array from all elements of another array
(24 answers)
Closed 8 months ago.
function destroyer(arr) {
const newArr = [...arguments[0]]
for(let i = 0; i < newArr.length; i++){
for(let j = 1; j < arguments.length; j++){
if(arguments[j] == newArr[i]){
newArr.splice(i,1)
console.log(newArr)
}
}
}
}
destroyer([3, 5, 1, 2, 2], 3, 5, 2);
New JS learner here.
Working on a problem that is supposed to look through the first arg in destroyer which will be an array and remove the elements that match the arguments following the array.
Results are [1,2] in the console output. Intended results are [1] with the given parameters Upon further testing it seems like the destroyer function is only removing the first instance of any value that it matches in newArr. If I take the second instance of '2' out of the test set it behaves as intended. I'm trying to understand what in my logic here is wrong. I've tried several different iteration patterns and can't seem to see what the problem is.
Thanks for any help!
I am going to link a few other answers here is this seems to be a fairly common question. The gist is that you are iterating over the live array while removing items from that array resulting in potentially skipping items.
How to iterate over an array and remove elements in JavaScript
Remove multiple elements from array in Javascript/jQuery
Alternatively you could also the filter method to help remove multiple values:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Try this:
function destroyer(arr) {
const newArr = [...arguments[0]]
for(let i = newArr.length - 1; i >= 0; i--){
for(let j = 1; j < arguments.length; j++){
if(arguments[j] == newArr[i]){
newArr.splice(i,1)
console.log(newArr)
}
}
}
}
This is an array pointer issue.
when i = 3 and j = 3, the function will match arguments[3] == newArr[3].
At this moment, newArr will be removed 1 element which is the first 2, and then the newArr becomes an new array that is [3,5,1,2].
The next index i is 4 which doesn't exist in the new newArr. So, the function will return and finish. That's why you get [3,5,1,2].
function destroyer (arg) {
if(!Array.isArray(arg)) return arg;
return arg.filter(x => !Array.prototype.slice.call(arguments, 1).includes(x))
}
It is because newArr is getting shorter as you splice it through your loops and the loop itself is also shortened.
see this probably your solution
This question already has answers here:
Find ith permutation in javascript
(3 answers)
Closed 4 years ago.
Despite reading a lot of Q/A about permutation/combination: Finding All Combinations of JavaScript array values + JavaScript - Generating combinations from n arrays with m elements I have not found the right way to get the kind of result I'm looking for.
I got a 10 values array:
var arr = [0,1,2,3,4,5,6,7,8,9];
If I'm right, the number of all possible permuted arrays of unique values (no duplicates):
[5,9,1,8,2,6,7,0,4,3] [4,8,0,2,1,9,7,3,6,5] ...
is 2x3x4x5x6x7x8x9x10 = 3628800
I'm trying to produce a function to dynamically create the 'n' array. For example:
function createArray(0) -> [0,1,2,3,4,5,6,7,8,9]
function createArray(45648) -> [0,1,5,3,2,8,7,9,6] (something like...)
function createArray(3628800) -> [9,8,7,6,5,4,3,2,1,0]
The way I'm figuring to achieve it is:
createArray(1) permutes the 2 last signs (8,9 -> 9,8)
createArray(2->6) permutes the 3 last signs (8,7,9 -> 9,8,7)
createArray(3628800) : all values are permuted (9->0)
Do you think it's possible/easy to do, and if yes how to proceed ?
[EDIT]
Thanks for helpfull answers
function permute(permutation, val) {
var length = permutation.length,
result = [permutation.slice()],
c = new Array(length).fill(0),
i = 1, k, p,
n = 0;
while (i < length) {
if (c[i] < i) {
if (n <= val) {
k = i % 2 && c[i];
p = permutation[i];
permutation[i] = permutation[k];
permutation[k] = p;
++c[i];
i = 1;
if (n == val) {
arr = permutation.slice();
console.log("n="+n+"\n"+arr);
console.log( 'Duration: '+((new Date() - t1)/1000)+'s' );
break;
}
else { n+=1; }
}
} else {
c[i] = 0;
++i;
}
}
}
let t1 = new Date();
permute([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 100000); // <- array requested
console : n=100000 + 0,5,8,1,7,2,3,6,4,9 + Duration: 0.004s
As this question doesn't decribe a specific programming problem but rather a task, and at that a rather complex one, you shoulnd't expect a full solution as an answer, but i'll try describing a possible method of doing this:
As you said, the number of permutations is 2x3x4x...
You could check if n > 2, if true, then check if n > 2x3, if true check if n > 2x3x4. That way you would know how many of the tailing array indexes you want to permutate. Then you would have to make sure to calculate the permutations in a sorted linear way that doesn't generate the same permutation twice. Thats a math problem, the coding itself should be rather easy (something along the lines of switch the position n times at changing indexes).
Not sure if this is the answer you're looking for, but making a unique permutation algorithm sounds rather complex (see for example this answer to another question https://stackoverflow.com/a/11425168/9521900) which links to this wikipedia article https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order on generating in lexicographic order.
EDIT: From Raj Sharmas comment on your question, this answer on generating permutations seems valuable too:
https://stackoverflow.com/a/37580979/3090583
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have four variables, a, b, c, and d, which each contain a number between 0 and 100, and I don't know the code to determine which one of the four variable contains the largest number.
I need to know the name of the variable that holds the highest value, not the highest value itself!
let a=8, b=1, c=9, d=3
let obj={a,b,c,d},
greatest=Object.values(obj).sort().pop()
key = Object.keys(obj).find( k => obj[k] === greatest )
console.log(key) // Logs "c"
Check out this, worked for me...
Math.max(a, b, c, d);
You can use this code. This also works for the negative integers, in case you have negative values in future. It will be useful for you.
var a=10, b=20, c=15, d = 5;
var array = [a, b, c, d];
var largest=a;
for (i=1; i<=array.length;i++){
if (array[i]>largest) {
largest=array[i];
}
}
console.log(largest);
You can use recursive calls.
Store all the variables in an array. Initial call is by doing findMax(a, a.length-1).
function findMax(a, index) {
if (index > 0) {
return Math.max(a[index], findMax(a, index - 1));
} else {
return a[0];
}
}
var x = findMax([1, 4, 50, 3], 3);
console.log(x);
//In inital call pass array.length -1
Sort the array in descending order and get the first one.
[a, b, c, d].sort(function(num1, num2){return num2-num1;})[0]
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Problem Statement
Watson gives Sherlock an array A of length N. Then he asks him to determine if there exists an element in the array such that the sum of the elements on its left is equal to the sum of the elements on its right. If there are no elements to the left/right, then the sum is considered to be zero. Formally, find an i, such that,
A1+A2...Ai−1=Ai+1+Ai+2...AN.
Input Format
The first line contains T, the number of test cases. For each test case, the first line contains N, the number of elements in the array A. The second line for each test case contains N space-separated integers, denoting the array A.
Output Format
For each test case print YES if there exists an element in the array, such that the sum of the elements on its left is equal to the sum of the elements on its right; otherwise print NO.
Constraints
1≤T≤10
1≤N≤105
1≤Ai≤2×104
1≤i≤N
Sample Input
2
3
1 2 3
4
1 2 3 3
Sample Output
NO
YES
Explanation
For the first test case, no such index exists. For the second test case,
A[1]+A[2]=A[4]
therefore index 3 satisfies the given conditions.
This solution features Array.prototype.some
The some() method tests whether some element in the array passes the test implemented by the provided function.
with a callback like
function isSherlock(_, i, a) {
function sum(i, n) {
return i < n ? a[i] + sum(i + 1, n) : 0;
}
return sum(0, i) === sum(i + 1, a.length);
}
where just the comparison is returned between the left side and the right side of the index, as well as it's recursive function
function sum(i, n) {
return i < n ? a[i] + sum(i + 1, n) : 0;
}
for counting the array values with the index smaller than the given value.
Alltogether as working example:
function isSherlock(_, i, a) {
function sum(i, n) {
return i < n ? a[i] + sum(i + 1, n) : 0;
}
return sum(0, i) === sum(i + 1, a.length);
}
document.write([1, 2, 3].some(isSherlock) + '<br>');
document.write([1, 2, 3, 3].some(isSherlock) + '<br>');
This question already has answers here:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
Closed 8 years ago.
Here is my question...
Given an array populated with numbers as a function parameter, produce a resulting array which contains any duplicates number from the array.
For example, given the array [ 1, 2, 4, 4, 3, 3, 1, 5, 3 ] it should return [1, 4, 3]. For extra bonus points return a sorted array.
I am starting out with Javascript - I know the language however, using it in the correct way ( as one should ) I'm still getting to grips with.
My pseudo code for this would be to:
Create an array with the numbers above var numbers = [1, 2, 4, 4, 3, 3, 1, 5, 3];
Then create an empty array named "result" var result = [];
Create a for loop that goes through the var numbers to check for duplicates which will then populate the empty array "result" with the duplicates
for (var i = 0;i < numbers.length; i++) {
//This is where I'm stuck...
}
I'm not sure what to do within the for loop to populate the var result and to throw in to the mix... The given array has to be a function parameter which makes sense so you can change the numbers in one place.
Any feedback on my thought process on this so far is greatly appreciated but ultimately I am wanting to learn how to achieve this.
Here is a JSFiddle of my progress so far... http://jsfiddle.net/fbauW/
One way of doing this (and it's not the only way) is by checking for existing elements in the array. Take a look at JavaScript's lastIndexOf function:
http://www.w3schools.com/jsref/jsref_lastindexof_array.asp
It will return -1 if the object does not exist in your array, and if it exists, will return an index of a later position than you are in. So you can use an if statement in your loop that checks whether or not there is another index containing your number, and add it in to your results array IF AND ONLY IF the index you get back != the index you are currently on (if they equal, this means that there is only one of that element in the list).
If you need more help, comment here and I can type some code in!
Good luck!
Array.prototype.contains = function(k) {
for ( var p in this)
if (this[p] === k)
return true;
return false;
};
//this prototype function checks if an element is already in the array or not
//go through all the array and push the element to result if it is not
//this way we can eliminate duplicates
//result will contain the resultant array
function findDuplicates(Numbers) {
var arrayLength = Numbers.length, i, j, result = [];
for (i = 0; i < arrayLength; i++) {
for (j = 0; j < arrayLength; j++) {
if (a[i] == a[j] && i != j && !result.contains(a[i])) {
result.push(a[i]);
}
}
}
return result;
}