making sure my array of random values doesn't contain duplicate values - javascript

I was wondering if anyone can advise how I can make sure the random array I'm generating from another array doesn't contain duplicate values, want to make sure that arr2 contains unique values?
JS
var limit = 5,
i = 0,
arr1 = [12, 14, 67, 45, 8, 45, 56, 8, 33, 89],
arr2 = [];
for ( i; i < limit; i++ ){
var rand = Math.floor((Math.random()*9)+1);
arr2.push( arr1[rand] );
}
console.log(arr2);
Maybe an if statement that compares arr1[rand] with arr2[i] ?

Create a temporary array that is a copy of arr1 containing only unique values:
// Copy unique values in arr1 into temp_arr
var temp_obj = {}, temp_arr = [], i;
for(i = arr1.length; i--;)
temp_obj[arr1[i]] = 1;
for(i in temp_obj)
temp_arr.push(i);
Then you can remove the element from temp_arr each time you add it to arr2. Since we used object keys when copying we have strings, so we can use + to convert them back to numbers when pushing into arr2:
arr2.push(+temp_arr.splice(rand, 1)[0]);
You should also change how you pick random numbers to:
var rand = Math.floor(Math.random()*temp_arr.length);
Whole code:
var limit = 5,
arr1 = [12, 14, 67, 45, 8, 45, 56, 8, 33, 89],
arr2 = [],
rand,
temp_obj = {},
temp_arr = []
i;
// Copy unique values from arr1 into temp_arr
for(i = arr1.length; i--;)
temp_obj[arr1[i]] = 1;
for(i in temp_obj)
temp_arr.push(i);;
// Move elements one at a time from temp_arr to arr2 until limit is reached
for (var i = limit; i--;){
rand = Math.floor(Math.random()*temp_arr.length);
arr2.push(+temp_arr.splice(rand, 1)[0]);
}
console.log(arr2);

The naive O(n^2) solution is to simply check each element and see if any other position in the array has the same value.
A linear time solution can be achieved using a hashset data structure. You can hack one in JavaScript using objects:
var set = {};
set['0'] = true;
set['1'] = true;
if(set.hasOwnProperty('0')) {
alert("duplicate 0!");
}
If the numbers are integers and relatively small, then you can keep track of them in an array of boolean values.

See http://bost.ocks.org/mike/shuffle/ for good info on the Fischer/Yates shuffle. For your problem, you could take the first five elements of the shuffled deck.

try this
for ( i; i < limit; i++ ){
var rand = Math.floor((Math.random()*9)+1);
for(j=0; j < arr1.length; j++)
if(rand == arr1[j]
{
blnfound = true;
break;
}
if(!blnfound)
arr2.push( arr1[rand] );
}

By using jQuery.inArray function :)
var limit = 5,
arr1 = [12, 14, 67, 45, 8, 45, 56, 8, 33, 89],
l = arr1.length,
arr2 = [];
while( limit ){
var tmp = arr1[ Math.random() * l | 0 ];
// for unsigned numbers '|0' construction works like Math.floor
if( !~$.inArray( tmp, arr2 ) ) {
// if not found $.inArray returns -1 ( == ~0 ), then !~-1 == true
limit--;
arr2[ arr2.length ] = tmp;
}
}
console.log( arr2 );

Related

Find the biggest number in an array by using JavaScript loops

Create a function called biggestNumberInArray().
That takes an array as a parameter and returns the biggest number.
Here is an array
const array = [-1, 0, 3, 100, 99, 2, 99]
What I try in my JavaScript code:
function biggestNumberInArray(arr) {
for (let i = 0; i < array.length; i++) {
for(let j=1;j<array.length;j++){
for(let k =2;k<array.length;k++){
if(array[i]>array[j] && array[i]>array[k]){
console.log(array[i]);
}
}
}
}
}
It returns 3 100 99.
I want to return just 100 because it is the biggest number.
Is there a better way to use loops to get the biggest value?
Using three different JavaScript loops to achieve this (for, forEach, for of, for in).
You can use three of them to accomplish it.
Some ES6 magic for you, using the spread syntax:
function biggestNumberInArray(arr) {
const max = Math.max(...arr);
return max;
}
Actually, a few people have answered this question in a more detailed fashion than I do, but I would like you to read this if you are curious about the performance between the various ways of getting the largest number in an array.
zer00ne's answer should be better for simplicity, but if you still want to follow the for-loop way, here it is:
function biggestNumberInArray (arr) {
// The largest number at first should be the first element or null for empty array
var largest = arr[0] || null;
// Current number, handled by the loop
var number = null;
for (var i = 0; i < arr.length; i++) {
// Update current number
number = arr[i];
// Compares stored largest number with current number, stores the largest one
largest = Math.max(largest, number);
}
return largest;
}
There are multiple ways.
Using Math max function
let array = [-1, 10, 30, 45, 5, 6, 89, 17];
console.log(Math.max(...array))
Using reduce
let array = [-1, 10, 30, 45, 5, 6, 89, 17];
console.log(array.reduce((element,max) => element > max ? element : max, 0));
Implement our own function
let array = [-1, 10, 30, 45, 5, 6, 89, 17];
function getMaxOutOfAnArray(array) {
let maxNumber = -Infinity;
array.forEach(number => { maxNumber = number > maxNumber ? number : maxNumber; })
console.log(maxNumber);
}
getMaxOutOfAnArray(array);
The simplest way is using Math.max.apply:
const array = [-1,0,3,100, 99, 2, 99];
function biggestNumberInArray(arr) {
return Math.max.apply(Math, arr);
}
console.log(biggestNumberInArray(array));
If you really want to use a for loop, you can do it using the technique from this answer:
const array = [-1,0,3,100, 99, 2, 99];
function biggestNumberInArray(arr) {
var m = -Infinity,
i = 0,
n = arr.length;
for (; i != n; ++i) {
if (arr[i] > m) {
m = arr[i];
}
}
return m;
}
console.log(biggestNumberInArray(array));
And you could also use reduce:
const array = [-1,0,3,100, 99, 2, 99];
function biggestNumberInArray(array) {
return array.reduce((m, c) => c > m ? c : m);
}
console.log(biggestNumberInArray(array));
I think you misunderstand how loops are used - there is no need to have three nested loops. You can iterate through the array with a single loop, keeping track of the largest number in a variable, then returning the variable at the end of the loop.
function largest(arr) {
var largest = arr[0]
arr.forEach(function(i) {
if (i > largest){
largest = i
}
}
return largest;
}
Of course you can do this much more simply:
Math.max(...arr)
but the question does ask for a for loop implementation.
This is best suited to some functional programming and using a reduce, for loops are out of favour these days.
const max = array => array && array.length ? array.reduce((max, current) => current > max ? current : max) : undefined;
console.log(max([-1, 0, 3, 100, 99, 2, 99]));
This is 70% more performant than Math.max https://jsperf.com/max-vs-reduce/1
Another visual way is to create a variable called something like maxNumber, then check every value in the array, and if it is greater than the maxNumber, then the maxNumber now = that value.
const array = [-1,0,3,100, 99, 2, 99];
function biggestNumberInArray(arr) {
let maxNumber;
for(let i = 0; i < arr.length; i++){
if(!maxNumber){ // protect against an array of values less than 0
maxNumber = arr[i]
}
if(arr[i] > maxNumber){
maxNumber = arr[i];
}
}
return maxNumber
}
console.log(biggestNumberInArray(array));
I hope this helps :)
var list = [12,34,11,10,34,68,5,6,2,2,90];
var length = list.length-1;
for(var i=0; i<length; i++){
for(j=0; j<length; j++){
if(list[j]>list[j+1]){
[ list[j] , list[j+1] ] = [ list[j+1] , list[j] ];
}
}
}
console.log(list[list.length-1]);
You Can try My codes to find the highest number form array using for loop.
function largestNumber(number){
let max = number[0];
for(let i = 0; i < number.length; i++){
let element = number[i];
if(element > max){
max = element;
}
}
return max;
}
let arrayNum= [22,25,40,60,80,100];
let result = largestNumber(arrayNum);
console.log('The Highest Number is: ',result);
let arr = [1,213,31,42,21];
let max = 0;
for(let i = 0; i < arr.length; i++) {
if(arr[i] > max) {
max = arr[i]
}
}
console.log(max)
There are multiple ways.
way - 1 | without for loop
const data = [-1, 0, 3, 100, 99, 2, 99];
// way - 1 | without for loop
const maxValue = Math.max(...data);
const maxIndex = data.indexOf(maxValue);
console.log({ maxValue, maxIndex }); // { maxValue: 100, maxIndex: 3 }
way - 2 | with for loop
const data = [-1, 0, 3, 100, 99, 2, 99];
// way - 2 | with for loop
let max = data[0];
for (let i = 0; i < data.length; i++) {
if (data[i] > max) {
max = data[i];
}
}
console.log(max); // 100
THis is the simple function to find the biggest number in array with for loop.
// Input sample data to the function
var arr = [-1, 0, 3, 100, 99, 2, 99];
// Just to show the result
console.log(findMax(arr));
// Function to find the biggest integer in array
function findMax(arr) {
// size of array
let arraySize = arr.length;
if (arraySize > 0) {
// Initialize variable with first index of array
var MaxNumber = arr[0];
for (var i = 0; i <= arraySize; i++) {
// if new number is greater than previous number
if (arr[i] > MaxNumber) {
// then assign greater number to variable
MaxNumber = arr[i];
}
}
// return biggest number
return MaxNumber;
} else {
return 0;
}
}
You can try this if you want to practice functions
const numbs = [1, 2, 4, 5, 6, 7, 8, 34];
let max = (arr) => {
let max = arr[0];
for (let i of arr) {
if (i > max) {
max = i;
}
}
return max;
};
let highestNumb = max(numbs);
console.log(highestNumb);
const array = [-1, 0, 3, 100, 99, 2, 99]
let longest = Math.max(...array);
what about this
const array = [1, 32, 3, 44, 5, 6]
console.time("method-test")
var largestNum = array[0]
for(var i = 1; i < array.length; i++) {
largestNum = largestNum > array[i] ? largestNum : array[i]
}
console.log(largestNum)
console.timeEnd("method-test")

How to split a large array into smaller array based upon given index values,

I have a large array e.g. aa=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
I have another array which holds the indexes values based upon which large array need to be chunked. e.g. cc=[10,16]
I want that array aa to be chunked into new arrays
dd[] = [from 0 to cc[0]index]
ee[] = [from cc[0]index to cc[next value]index]
EXAMPLE
dd[] = [1,2,3,4,5,6,7,8,9,10]
ee[] = [11,12,13,14,15,16]
and so on until cc[] has indexes
I could not figure out the logic, if anyone can help me please.
You could use Array#map and Array#slice for the parts.
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
indices = [10, 16],
result = indices.map(function (a, i, aa) {
return array.slice(aa[i - 1] || 0, a);
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
you can use the new and simple array.slice:
var array=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
var i,j,temparray,chunk = 10;
for (i=0,j=array.length; i<j; i+=chunk) {
temparray = array.slice(i,i+chunk);
console.info(temparray);
}
You can do something like this if you don't wanna use build in methods.
function createChunks(aa, cc) {
var temp = [], chunks = [];
for(var i=0, j=0, k=0; i<aa.length; i++) {
if(aa[i] == cc[j]) {
temp[k] = aa[i];
chunks.push(temp);
temp = []; k=0; j++;
}
else
temp[k++] = aa[i];
}
return chunks;
}
var aa=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16], cc=[10, 16];
var chunks = createChunks(aa, cc);
console.log(JSON.stringify(chunks));

Search An Array Consisting of Sub-Arrays For the Largest Number and Return in a New Array

I am working on a coding challenge to take a given array which consists of sub-arrays, search for the largest number in each sub-array, and finally return a new array consisting only of the largest numbers. My thought process was to create variables out of each subarray, write a for-loop comparing each value within the array, then push the largest value to a new array. After writing my first for-loop I tested my code and see that I am getting an unexpected result of the entire first subarray being pushed into my new array. I am looking for the mistake before I write the next three loops. Thank you. Edit: This is for beginner JavaScript coders and the suggestion indicates to use comparison operators in your solution.
function largestOfFour(arr) {
var one = arr[0];
var two = arr[1];
var three = arr[2];
var four = arr[3];
var newArr = [];
for (var i = 0; i < one.length; i++){
var oneLrg = 0;
if (one[i] > oneLrg){
oneLrg = one[i];
}
newArr.push(oneLrg);
}
return arr;
}
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])); //This test case returns [4,5,1,3] instead of just [5]
Using >:
var newArr = [];
for(var i=0; i<arr.length; ++i) { // Iterate array
var maximum = -Infinity; // Initial maximum
for(var j=0; j<arr[i].length; ++j) // Iterate subarrays
if(arr[i][j] > maximum) // Compare
maximum = arr[i][j]; // Update maximum
newArr.push(maximum); // Store the real maximum
}
Using Math.max:
var newArr = [];
for(var i=0; i<arr.length; ++i) { // Iterate array
var maximum = -Infinity; // Initial maximum
for(var j=0; j<arr[i].length; ++j) // Iterate subarrays
maximum = Math.max(maximum, arr[i][j]); // Update maximum
newArr.push(maximum); // Store the real maximum
}
Adding apply:
var newArr = [];
for(var i=0; i<arr.length; ++i) // Iterate array
newArr.push( // Store ...
Math.max.apply(Math, arr[i]) // ... the maximum of the subarray
);
Adding ECMAScript 5 map,
var newArr = arr.map(function(subarray) {
return Math.max.apply(Math, subarray);
});
Adding ECMAScript 5 bind,
var newArr = arr.map(Function.apply.bind(Math.max, Math));
Or adding ECMAScript 6 arrow functions and spread operator,
var newArr = arr.map(subarray => Math.max(...subarray));
The problem here is that you're overwriting oneLrg at each loop iteration, and pushing it inside the same loop, so you're comparing each value to 0 and then, as one[i] is bigger, saving it.
Try this:
var oneLrg = 0;
for (var i = 0; i < one.length; i++){
if (one[i] > oneLrg){
oneLrg = one[i];
}
}
newArr.push(oneLrg);
No doubt that #Austin Hansen and I are leveraging the same learning environment for this challenge: Free Code Camp.
Having just worked through this challenge myself (FCC calls them "Bonfires"), I figured I'd provide solution that heavily dovetails from #Oriol 's excellent ">" solution.
I've included a specific note about the code blocks because to us newbies (at FCC or elsewhere), the absence of such can give us fits for hours : )
function largestOfFour(arr) {
var finalArray = [];
for(i = 0; i < arr.length; i++) { // iterates through each array
var max = -Infinity;
for(j = 0; j < arr[i].length; j++) { // iterates through each sub-array
if(arr[i][j] > max) { // comparing each successive element within the sub-array to what is currently stored as max
max = arr[i][j]; //if the ">" comparison is true then max gets updated
}
}
finalArray.push(max); // ensure this is OUTside of the j for loop. putting it INside the j for loop returns a very long (and wrong) array. try it.
}
console.log(finalArray);
return finalArray;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]], "");
https://jsbin.com/puweci/edit?js,console
FCC recognizes the follow solution which doesn't NOT leverage Array.push().
function largestOfFour(arr) {
var results = [];
for (var i = 0; i < arr.length; i++) {
var max = -Infinity;
for (var j = 0; j < arr[i].length; j++) {
if (arr[i][j] > max) {
max = arr[i][j];
}
}
results[i] = max;
}
return results;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]], "");
This function will take two numbers and return their maximum:
var greatest = function(a,b){ return Math.max(a,b); };
This function will take an array of numbers and apply the greatest function to each number in turn (using the .reduce( callbackFunction, initialValue ) method of arrays) to get the maximum value in the array:
var findMaximum = function( arr ){ return arr.reduce( greatest, Number.NEGATIVE_INFINITY ); };
The findMaximum function can be simplified by just calling Math.max() with all the array values (eliminating the need for the greatest function); like this:
var findMaximum = function( arr ){ return Math.max.apply( Math, arr ); };
This function will take an array (of arrays) and call findMaximum on each element of it and return a new array containing those maximums (using the .map( callbackFunction ) method on an array):
var largestOfFour = function( arr ){ return arr.map( findMaximum ); };
This post hasn't had any new updates in about 3 months, but I figured I would post my solution to this problem as it looks a bit different than most of the other solutions posted thus far. Figured someone might find it helpful!
I am using quite a few built in method functions( .forEach, .sort, .push, .shift) a quick google search will explain each of these fairly well if you are unsure of how they work. https://developer.mozilla.org is a great resource for these.
function largestOfFour(arr) {
var newArr = []; //set up new empty array
arr.forEach(function(subArr){ //iterate through array with .each function
subArr.sort(function(a, b){ //use .sort to place largest number of each subarray into index[0]
return a < b;
});
newArr.push(subArr.shift()); //use .push method to .shift the index[0] number to newArr
});
return newArr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
You can have a look at this:
function largestOfFour(arr) {
var newArr=[];
largestnum=0;
for(i=0;i<arr.length;i++)
{
for(j=0;j<4;j++)
{
if(arr[i][j]>largestnum)
largestnum=arr[i][j];
}
newArr.push(largestnum);
largestnum=0;
}
return newArr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
#orion - Your answer to me was not working. If the push is inside the if statement was pushing numbers that were not suppose to be in the array. As a result the first would push [4,5] and wound't work. So I moved the push out of the for statement and reset the lgstNumber to 0 also after so it wouldn't use it for the next sub-array. This worked for me...
function largestOfFour(arr) {
// You can do this!
var newArr = [];
var lgstNumber = - Infinity;
for(var i = 0; i < arr.length; i++){
for(var j = 0; j < arr[i].length; j++){
if(lgstNumber < arr[i][j]){
lgstNumber = arr[i][j];
}
}
newArr.push(lgstNumber);
lgstNumber = 0;
}
return newArr;
}
function largestOfFour(arr) {
return arr.map(function(subArray) {
return subArray.reduce(function(firstArray, secondArray) {
return firstArray > secondArray ? firstArray : secondArray;
});
});
}
largestOfFour([[13, 27, 18, 26],[4, 5, 1, 3],[32, 35, 37, 39],[1000, 1001, 857, 1]
]);
its more efficient.
function largestOfFour(arr) {
for(var x=0;x<arr.length;x++)
{
for(var y=0;y<arr[x].length;y++)
{
arr[x]=arr[x].sort(function(a,b)
{
return b-a;
});
}
}
var array=[];
for(var a=0;a<arr.length;a++)
{
for(var b=0;b<arr[a].length;b++)
{
if(b==0)
{
array[a]=arr[a][b];
}
}
}
return array;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

How to join two arrays into one two-dimensional array?

I have two arrays. How can I join them into one multidimensional array?
The first array is:
var arrayA = ['Jhon, kend, 12, 62626262662',
'Lisa, Ann, 43, 672536452',
'Sophie, Lynn, 23, 636366363'];
My other array has the values:
var arrayB = ['Jhon', 'Lisa', 'Sophie'];
How could I get an array with this format??
var jarray = [['Jhon', ['Jhon, kend, 12, 62626262662']],
['Lisa', ['Lisa, Ann, 43, 672536452']],
['Sohphie', ['Sophie, Lynn, 23, 636366363']]]
var jarray = [];
for (var i=0; i<arrayA.length && i<arrayB.length; i++)
jarray[i] = [arrayB[i], [arrayA[i]]];
However, I wouldn't call that "multidimensional array" - that usually refers to arrays that include items of the same type. Also I'm not sure why you want the second part of your arrays be an one-element array.
Here is a map version
const arrayA = ['Jhon, kend, 12, 62626262662',
'Lisa, Ann, 43, 672536452',
'Sophie, Lynn, 23, 636366363'];
const arrayB = ['Jhon', 'Lisa', 'Sophie'];
/* expected output
var jarray = [['Jhon', ['Jhon, kend, 12, 62626262662']],
['Lisa', ['Lisa, Ann, 43, 672536452']],
['Sohphie', ['Sophie, Lynn, 23, 636366363']]] */
const jarray = arrayB.map((item,i) => [item,[arrayA[i]]]);
console.log(jarray);
You can use Underscore.js http://underscorejs.org/#find
Looks through each value in the list, returning the first one that passes a truth test (iterator). The function returns as soon as it finds an acceptable element, and doesn't traverse the entire list.
var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> 2
Then, you can make the same with the array B elements and by code, make a join.
This is what I did to get what you were asking:
var jarray = [];
for (var i = 0; i < arrayB.length; i++) {
jarray[i] = [];
jarray[i].push(arrayB[i]);
var valuesList = [],
comparator = new RegExp(arrayB[i]);
for (var e = 0; e < arrayA.length; e++) {
if (comparator.test(arrayA[e])) {
valuesList.push(arrayA[e]);
}
}
jarray[i].push(valuesList);
}

How to merge two different arrays in Javascript?

I have this array,
var arr1 = [19, 1, 1, 1, 1];
and another array,
var arr2 = ["Default", "Dynamic", "Assessment", "Risk", "Privacy"];
What I would like is to merge them somehow such that it would look something like this,
var merged_array = [ ["Default", 19], ["Dynamic", 1], ["Assessment", 1], ["Risk", 3], ["Privacy", 2] ];
how would I do that? I tried join but I did not achieve what I wanted. Thanks in advance!
Using a for loop:
var merged_array = new Array(arr1.length);
for (var i = 0; i < arr1.length; i++) {
merged_array[i] = new Array(arr2[i], arr1[i]);
}
This assumes arr1 and arr2 have the same length.
If you have jquery or equivalent:
var merged_array = $.map(arr1, function(e, i) {
return [arr2[i], e];
});
If not, then just use a for loop, same idea.
var merged_array = []
for (var i = 0; i < arr1.length && i < arr2.length; i++) {
merged_array[i] = [arr2[i], arr1[i]];
}
var result = new Array();
for (var i=0; i<arr1 .length && i<arr2.length ; i++) {
result[i] = new Array();
result[i][0] = arr1[i];
result[i][1] = arr2[i];
}
I'd probably extend the array object especially if this is a common task. Something like this:
Array.prototype.myMerge = function(arr){
var returnArr = [];
for(var i = 0, len = this.length; i < len; i++){
returnArr[i] = [this[i], arr[i]];
}
return returnArr;
};
then you could call it like this:
var merged_array = arr1.myMerge(arr2)
Of course you'd have to add some error checking on the length of the arrays, this function assumes that arr1 is longer or the same length as arr2. But that depends on what you want to do if arr1 and arr2 are different lengths, your question seems to assume they are the same length.
If you include the library underscore.js (prototype.js also has something similar), you can use _.zip(array1,array2). They provide example usage with 3 arrays.
From http://underscorejs.org/#zip :
zip_.zip(*arrays)
Merges together the values of each of the arrays with the values at the corresponding position. Useful when you have separate data sources that are coordinated through matching array indexes. If you're working with a matrix of nested arrays, zip.apply can transpose the matrix in a similar fashion.
_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
=> [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]

Categories

Resources