Related
For some reason, the manipulated doubleArray below is not shown in the console. Any variables that I declare after the for loop won't show to the console on both cases. Consider that in the first algorithm, there is only one for loop with x being incremented everytime. Whereas, in the second algorithm, it's a nested for loop. Can someone help me fix my error in both algorithms?
First Algorithm:
var isDuplicate = function() {
var helloWorld = [1,2,3,4,3];
var doubleValue = [];
var x = 0;
for (i = 0; i < helloWorld.length; i++) {
x = x + 1;
if (helloWorld[i] === helloWorld[x] && i !== x) {
doubleValue.push(helloWorld[i])
console.log(helloWorld[i]);
} else {
continue;
}
}
console.log(doubleValue);
};
The second Algorithm:
var isDuplicate = function() {
var helloWorld = [1,2,3,4,3];
var doubleValue = [];
for (i = 0; i < helloWorld.length; i++) {
for (x = 1; x < helloWorld.length; i++) {
if (helloWorld[i] === helloWorld[x] && i !== x) {
doubleValue.push(helloWorld[x]);
}
}
}
console.log(doubleValue);
};
In first algorithm, you are only checking if the number at current index is equal to the number at the next index, meaning you are only comparing numbers at consecutive indexes. First algorithm will work only if you have duplicate numbers on consecutive indexes.
In second algorithm, you are incrementing i in both loops, increment x in nested loop, change x = 1 to x = i + 1 and your error will be fixed.
Here's the fixed second code snippet
var isDuplicate = function() {
var helloWorld = [1,2,3,4,3, 1, 2];
var doubleValue = [];
for (let i = 0; i < helloWorld.length; i++) {
for (let x = i + 1; x < helloWorld.length; x++) {
if (helloWorld[i] === helloWorld[x] && i !== x) {
doubleValue.push(helloWorld[x]);
}
}
}
console.log(doubleValue);
};
isDuplicate();
Heres's another way to find the duplicates in an array, using an object. Loop over the array, if current number is present as key in the object, push the current number in the doubleValue array otherwise add the current number as key-value pair in the object.
const isDuplicate = function() {
const helloWorld = [1,2,3,4,3, 1, 2];
const doubleValue = [];
const obj = {};
helloWorld.forEach(n => obj[n] ? doubleValue.push(n): obj[n] = n);
console.log(doubleValue);
};
isDuplicate();
Not entirely sure what you are trying to do. If you are only looking for a method to remove duplicates you can do the following:
const hello_world = [1, 2, 2, 3, 4, 5, 5];
const duplicates_removed = Array.from(new Set(hello_world));
A set is a data object that only allows you to store unique values so, when converting an array to a set it will automatically remove all duplicate values. In the example above we are creating a set from hello_world and converting it back to an array.
If you are looking for a function that can identify all the duplicates in an array you can try the following:
const hello_world = [1, 2, 2, 3, 4, 5, 5];
const duplicates_found = hello_world.filter((item, index) => hello_world.indexOf(item) != index);
The main problem by finding duplicates is to have nested loop to compare each element of the array with any other element exept the element at the same position.
By using the second algorithm, you can iterate from the known position to reduce the iteration count.
var isDuplicate = function(array) {
var doubleValue = [];
outer: for (var i = 0; i < array.length - 1; i++) { // add label,
// declare variable i
// no need to check last element
for (var j = i + 1; j < array.length; j++) { // start from i + 1,
// increment j
if (array[i] === array[j]) { // compare values, not indices
doubleValue.push(array[i]);
continue outer; // prevent looping
}
}
}
return doubleValue;
};
console.log(isDuplicate([1, 2, 3, 4, 3])); // [3]
You could take an object for storing seen values and use a single loop for getting duplicate values.
const
getDuplicates = array => {
const
seen = {}
duplicates = [];
for (let value of array) {
if (seen[value]) duplicates.push(value);
else seen[value] = true;
}
return duplicates;
};
console.log(getDuplicates([1, 2, 3, 4, 3])); // [3]
Your first algorithm doesn't work because it only looks for duplicates next to each other. You can fix it by first sorting the array, then finding the duplicates. You can also remove the x and replace it by ++i in the loop.
var isDuplicate = function() {
var helloWorld = [1,2,3,4,3,6];
var doubleValue = [];
helloWorld = helloWorld.sort((a, b) => { return a - b });
for (i = 0; i < helloWorld.length; i++) {
if (helloWorld[i] === helloWorld[++i]) {
doubleValue.push(helloWorld[i])
console.log(helloWorld[i]);
} else {
continue;
}
}
console.log(doubleValue);
};
isDuplicate();
For the second algorithm loop, you probably meant x++ instead of i++ in the second loop. This would fix the problem.
var isDuplicate = function() {
var helloWorld = [1,2,3,4,3,4];
var doubleValue = [];
for (i = 0; i < helloWorld.length; i++) {
for (x = i + 1; x < helloWorld.length; x++) {
if (helloWorld[i] === helloWorld[x]) {
doubleValue.push(helloWorld[x]);
}
}
}
console.log(doubleValue);
};
isDuplicate()
The first algorithm can't be fixed, it can only detect consecutive duplicates,
in the second algorithm you increment i in both loops.
To avoid the duplicates beeing listed too often, you should start the second loop with i + 1
In Javascript:
I have an existing array like [4,5,6,10] - (These are 'repid').
I have an ajax response like [{"repid":5,"avgAmount":2.5},{"salesrepid":10,"avgAmount":3.0}].
I have to build a third array which will compare the 'repids' of the 2 arrays and build a third array so that it will place a '0' if the repids do not match or else the 'avgAmount' if they match.
So, in my case above, I would 'build' a third array:
[0, 2.5, 0, 3.0]
I've tried many variances of:
//need to assign the sales average values to the proper repid
for (var i = 0; i < repIds.length; i++) {
for (var j = 0; j < salesrepids.length; j++) {
if (repIds[i] == salesrepids[j]) {
salesvalues.push(key.avgAmount);
} else { salesvalues.push("0"); }
};
}
}
}
You need to address the correct keys of your objects. And also only add the 0 in case you don't find any matching entry:
var repIds = [4, 5, 6, 10];
var salesrepids = [{"repid": 5, "avgAmount": 2.5}, {"repid": 10, "avgAmount": 3.0}]
var salesvalues = [];
for (var i = 0; i < repIds.length; i++) {
var noMatch = true;
for (var j = 0; j < salesrepids.length; j++) {
if (repIds[i] === salesrepids[j]['repid']) {
salesvalues.push(salesrepids[j]['avgAmount']);
noMatch = false;
}
}
if (noMatch) {
salesvalues.push(0);
}
}
console.log(salesvalues);
You can do something like using map and find:
Loop through the first array -> Check if the id exists in the second array using find -> If yes, return it's avgAmount else return 0.
const ids = [4,5,6,10],
amounts = [{"repid":5,"avgAmount":2.5},{"repid":10,"avgAmount":3.0}];
const output = ids.map(i => {
const found = amounts.find(a => a.repid === i);
return found ? found.avgAmount : 0;
})
console.log(output)
May be like this:
var repids = [4,5,6,10];
var returns = [{"repid":5,"avgAmount":2.5},{"salesrepid":10,"avgAmount":3.0}];
var results = [];
for(var key in returns){
if(repids.includes(returns[key].repid)){
results.push(returns[key].repid);
results.push(returns[key].avgAmount);
}
if(repids.includes(returns[key].salesrepid)){
results.push(returns[key].salesrepid);
results.push(returns[key].avgAmount);
}
}
console.log(results);
Starting with this initial 2D array:
var initialArray = [[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]];
I need to create this 3D array programmatically:
var fullArray = [
[[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]],
[[3,4],[0,1],[5,6],[2,3],[6,7],[3,4]],
[[4,5],[1,2],[6,7],[3,4],[0,1],[4,5]],
[[5,6],[2,3],[0,1],[4,5],[1,2],[5,6]],
[[6,7],[3,4],[1,2],[5,6],[2,3],[6,7]],
[[0,1],[4,5],[2,3],[6,7],[3,4],[0,1]],
[[1,2],[5,6],[3,4],[0,1],[4,5],[1,2]],
[[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]],
[[3,4],[0,1],[5,6],[2,3],[6,7],[3,4]],
[[4,5],[1,2],[6,7],[3,4],[0,1],[4,5]],
[[5,6],[2,3],[0,1],[4,5],[1,2],[5,6]]
];
See the pattern?
On each pair, the [0] position should increment to 6 (from any starting number <= 6) and then reset to 0 and then continue incrementing. Similarly, the [1] position should increment to 7 (from any starting number <= 7) and then reset to 1 and then continue incrementing.
In this example, there are 10 2D arrays contained in the fullArray. However, I need this number to be a variable. Something like this:
var numberOf2DArraysInFullArray = 12;
Furthermore, the initial array should be flexible so that initialArray values can be rearranged like this (but with the same iteration follow-through rules stated above):
var initialArray = [[6,7],[2,3],[5,6],[4,5],[1,2],[6,7]];
Any thoughts on how to programmatically create this structure?
Stumped on how to gracefully pull this off.
Feedback greatly appreciated!
Here's a solution, I've separated the methods, and I made it so if instead of pairs it's an N size array and you want the [2] to increase up to 8 and reset to 2, if that's not needed you can simplify the of the loop for(var j = 0; j < innerArray.length; j++)
var initialArray = [[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]];
var create3DArray = function(array, size){
var newArray = [initialArray];
for(var i = 0; i < size; i++)
{
newArray.push(getNextArrayRow(newArray[i]));
}
return newArray;
}
var getNextArrayRow = function(array){
var nextRow = [];
for(var i = 0; i < array.length; i++)
{
var innerArray = array[i];
var nextElement = [];
for(var j = 0; j < innerArray.length; j++)
{
var value = (innerArray[j] + 1) % (7 + j);
value = value === 0 ? j : value;
nextElement.push(value);
}
nextRow.push(nextElement);
}
return nextRow;
}
console.log(create3DArray(initialArray,3));
Note, the results from running the snippet are a bit difficult to read...
var initialArray = [[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]];
var numOfArrays = 10;
// get a range array [0, 1, 2, ...]
var range = [];
for (var i = 0; i < numOfArrays; i++) {
range.push(i);
}
var result = range.reduce(function(prev, index) {
if (index == 0) {
return prev;
}
prev.push(transformArray(prev[index - 1]));
return prev;
}, [initialArray])
console.log(result);
function transformArray(arr) {
return arr.map(transformSubArray)
}
function transformSubArray(arr) {
return arr.map(function(val) {
return val == 7 ? 0 : val + 1;
})
}
Here's a pretty simple functional-ish implementation
I want to display an array without showing of indexes. The for loop returns the array indexes which is not showing in usual declaration.
I want to send an array like [1,2,3 ...] but after retrieving from for loop, I haven't the above format. How can I store my values as above.
var a = [];
for (var i = 1; i < 8; i++) {
a[i] = i;
};
console.log(a);
Outputs:
[1: 1, 2: 2 ...]
Desired output:
[1,2,3]// same as console.log([1,2,3])
Array indices start at zero, your loop starts at 1, with index 0 missing you have a sparse array that's why you get that output, you can use push to add values to an array without using the index.
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);
The problem is that you start your array with 1 index, making initial 0 position being empty (so called "hole" in array). Basically you treat array as normal object (which you can do of course but it defeats the purpose of array structure) - and because of this browser console.log decides to shows you keys, as it thinks that you want to see object keys as well as its values.
You need to push values to array:
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
I have to disagree with the answers provided here. The best way to do something like this is:
var a = new Array(7);
for (var i = 0; i < a.length; i++) {
a[i] = i + 1;
}
console.log(a);
Your code is making each index equal to i, so use it this way
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);
var UserBoard = new Array(20,20);
for(var i = 0; i < 21; ++i){
for(var j = 0; j < 21; ++j){
UserBoard[i,j] = 0;
}
}
document.write(UserBoard[3,5]);
UserBoard[4,5]=1;
document.write(UserBoard[3,5]);
http://jsfiddle.net/XbyqN/2/
it's quite simple but I don't know why does this. Alert should be 0, not 1 since I've initialized the 2d array to 0.
Can someone explain me why?
Let's break it down
var UserBoard = new Array(20,20);
You are creating an array with two slots, both of them containing the value "20" (int). So your array is [20, 20]
Next, your loop :
for(var i = 0; i < 21; ++i){
for(var j = 0; j < 21; ++j){
UserBoard[i,j] = 0;
}
}
Two dimensional arrays are not defined like this. In that case, only the "j" counter does something. The "i" is simply ignored. So you end up with an array as follow : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Next, the assignement :
UserBoard[4,5]=1;
Is equivalent to :
UserBoard[5]=1;
And your alert :
alert("test: " + UserBoard[3,5]);
Is equivalent to :
alert("test: " + UserBoard[5]);
That's why you get "1" as alert.
If you want two dimensional arrays, you should use the following notation :
UserBoard[4][5] = 1;
Read it all here on MDN : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array
You want UserBoard[i][j] instead of UserBoard[i,j].
Multidimensional arrays don't work as you seem to think they work. They're, in fact, arrays of arrays.
Use this :
var UserBoard = new Array(20);
for(var i = 0; i < 20; ++i){
UserBoard[i] = new Array(20);
for(var j = 0; j < 20; ++j){
UserBoard[i][j] = 0;
}
}
I suggest you start using console.log and Chrome's developer tool to debug your code (or Firebug). Try this at the end of your code and then type the F12 key :
console.log(UserBoard);
The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.
var UserBoard = new Array(20,20); // [20, 20]
for(var i = 0; i < 21; ++i){
for(var j = 0; j < 21; ++j){
UserBoard[i,j] = 0; // UserBoard[j] = 0
}
}
UserBoard[4,5]=1; // UserBoard[5] = 1
alert("test: " + UserBoard[3,5]); // UserBoard[5]
What you want is:
var UserBoard = [];
for (var i = 0; i < 20; i++) { // i < 20
UserBoard[i] = [];
for (var j = 0; j < 20; j++) {
UserBoard[i][j] = 0;
}
}
UserBoard[4][5]=1;
alert("test: " + UserBoard[3][5]);
When creating a new array using the array constructor (new Array), the arguments have different meanings, depending on the type and total number of arguments.
var array20long = new Array(20);// = [undefined,undefined,undefined,....].length === 20
var arrayString = new Array('foo');// = ['foo']
var yourArray = new Array(20,20);// = [20,20]
Put simply: passing 1 integer to the array constructor, creates an array with length equal to the int passed, passing several integers will result in 1, 1 dimensional array with a length equal to the total number of argumens. In your case, two integers creating an array with 2 values. Each index will be initialized to its corresponding argument. In your case: index 0 === 20, index 1 === 20, if you had written new Array(20,10), the result would be an array like [20,10].
You get the basic idea.It is important to note that accessing multi dimensional arrays using a comma won't work: instead of writing arr[1,2] you should have written arr[1][2]. Google some introductory tutorials to JavaScript, it won't hurt... and you'll soon learn why using the array constructor isn't the best way of creating arrays