This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 2 years ago.
First let me say am a novice at Javascript so this may be more obvious than I think. But what I'm trying to do is create a new Javascript array from two existing arrays. My thinking is to create a for loop, test if they are equal and if not push that number into a new array. For example.
var allArr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
var myArr = [7,8,9,10,14,17];
var fnlArr = [];
What I would like to end up with is fnlArr = [1,2,3,4,5,6,11,12,13,15,16,18,19,20];
Something like:
for (n = 0; n < myArr.length; n++){
for (p = 0; p < allArr.length; p++){
if (p!==myArr[n]){
fnlArr.push(p);}
}
}
I was also thinking maybe to grep to see if they are the same???
Any help would be appreciated.
You can use .filter:
const allArr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
const myArr = [7,8,9,10,14,17];
const set = new Set(myArr);
const fnlArr = allArr.filter(e => !set.has(e));
console.log(fnlArr);
Related
This question already has answers here:
Getting a random value from a JavaScript array
(28 answers)
Closed 4 months ago.
Make sentences from the three arrays. Firt index with first index form each array so on..
10 sentences. (This I have figured out and managed)
Use Math.random to mix the words from the arrays randomly to make new sentences, doesnt matter if a word get used two times.
Question: where do i best put the Math.random in my code?
let substantiv = ['Daddy', 'Jag', 'Hästen', 'Mamma', 'Glaset', 'Gameboy', 'Pelle','Blondie', 'Sängen', 'Bilen']
let verb = ['cyklar', 'rider', 'bakar', 'springer', 'hoppar', 'äter', 'dricker', 'går', 'läser', 'sover']
let adj = ['bra', 'dåligt', 'roligt', 'inte', 'alltid', 'på Söndag', 'aldrig', 'imorgon', 'idag', 'snabbt']
let cont = document.createElement('div')
document.body.append(cont)
for(let i=0; i<10; i++){
const el1 = document.createElement('div')
el1.textContent = `${substantiv[i]} `+`${verb[i]} `+`${adj[i]}`
cont.append(el1)
}
I found this solution;
for(let i=0; i<10; i++){
const random1 = Math.floor(Math.random()* substantiv.length)
const random2 = Math.floor(Math.random()* verb.length)
const random3 = Math.floor(Math.random()* adj.length)
const el2 = document.createElement('div')
el2.textContent = `${substantiv[random1]} ${verb[random2]} ${adj[random3]}`
cont.append(el2)
}
This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 5 years ago.
I want to optimize my javascript code with a FOR by i can't do this and i don't know why.
My code :
let pokemon1 = 'premier';
let pokemon2 = 'second';
let pokemon3 = 'troisieme';
for (var i = 1; i < 4; i++) {
console.log(pokemon[i]);
}
Do you know why it doesn't work ?
Thank you very much and sorry if i am a noob.
You should place the pokemon in an array:
let pokemon = [];
pokemon[0] = "premier";
pokemon[1] = "second";
pokemon[2] = "troisieme";
for(var i = 0; i < pokemon.length; i++){
console.log(pokemon[i])
};
Followed by some reading time: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration
Since you are using a list, you should use [] to define an array :
let pokemons = ['premier', 'second', 'troisième'];
for (let i = 0; i < pokemons.length; i++) {
console.log(pokemons[i]);
}
See https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array for more information.
Also you should note that the first element of a list is 0.
So basically pokemons[0] === 'premier and pokemons[2] === 'troisième'
This question already has answers here:
Javascript Object push() function
(10 answers)
Closed 8 years ago.
I have a object for which i am using push method and it gives me length one more than expected.
var Object=[];
var temp = {};
var j=0;
while(j<2){
temp.id= j+1;
//other properties setting
Object.push(temp);
j++;
}
console.log(Object.length);
gives me 3. Also I see three object values, first as empty second has id =1 and third has id =2.
.push is a function of Array and not Object and don't use variable names that cause ambiguity.
Use:
var arr = [];
var temp = {};
var j = 0;
while (j < 2) {
temp.id = j + 1;
//other properties setting
arr.push(temp);
j++;
}
console.log(arr.length);
This question already has answers here:
Split array into chunks
(73 answers)
Closed 8 years ago.
I am new to javascript. I have a list of 500 or more items. I need split this array into sub arrays each containing 20 items. i.e 25 arrays if there are exactly 500 items and each array containing 20 items. I created 25 arrays like below:
var firstSet=[];
var secondSet=[];
.....
And i populate each of this array using the for loop. In javascript how can I make it programmatically since the main list can return more than 500 items in future and each sub array should be configured for more than 20 items in future. What is the best solution to fix this situation?
As comments say, you should split it with a 2 dimentional array:
var mainArray=[1,2,3,4,5,6,7,8,9,10];
function splitArray(arr,qty){
var mainArr=[], subarr=[];
for(var i=0;i<arr.length;i++){
subarr.push(arr[i]);
if( ((i+1) % qty == 0) || i+1==arr.length){
mainArr.push(subarr);
subarr=[];
}
}
return mainArr;
}
console.log(splitArray(mainArray,2));
This creates 1 array with 5 indexes. In each index, you have an array of 2 elements. So it groups it in [1,2], [3,4], [5,6], [7,8], [9,10]
Use nested loops to create a 2-dimensional array from the original data.
var sets = [];
var items_per_set = 20;
for (var i = 0, outer = 0; i < list.length; i += items_per_set, outer++) {
sets[outer] = [];
var limit = Math.min(list.length, i+items_per_set);
for (j = i; j < limit; j++) {
sets[outer].push(list[j]);
}
}
This question already has answers here:
How to randomize (shuffle) a JavaScript array?
(69 answers)
Closed 9 years ago.
I am trying to make a script which is outputting every number from 1-10.
Using a random number generator, in JavaScript.
I want every number to be unique.
Here is an example of what i would like the script to output:
5 9 7 6 1 3 4 8 2 10
This is my attempt:
var test = [];
var amountOfNumbers = 10;
var inArray = false;
var useNumbers = [];
for(var i=0; useNumbers.length<=amountOfNumbers; i++){
var rng = Math.floor((Math.random()*amountOfNumbers)+1);
for(var a=0; a<=test.length; a++){
if(rng == test[a]){
inArray == true;
}
}
if(!inArray){
document.write(rng);
test.push(rng);
useNumbers.push(rng);
}
}
Hope you can help.
for the record I am not interested in jQuery og any other library :)
1) How to fix your code
You have a few errors, among them the fact you don't reset inArray to false and that you don't iterate over the whole test array (use <, not <=). But using a loop to see if you already have the number isn't efficient, it's better to use an object as a map :
var test = [];
var amountOfNumbers = 10;
var useNumbers = {};
for(var i=0; test.length<amountOfNumbers; i++){
var rng = Math.floor((Math.random()*amountOfNumbers)+1);
if(!useNumbers[rng]){
document.write(rng);
test.push(rng);
useNumbers[rng] = true;
}
}
2) How to do it properly
Your algorithm will loop until it is lucky enough to find the remaining numbers. This isn't efficient and isn't predictable. The normal reliable practice is
to generate the array [1..10]
to shuffle it
Generating an array of the integers from 1 to N can be done with a simple loop or in a fancier way :
var arr = Array.apply(0,new Array(N)).map(function(_,i){ return i+1 });
Shuffling an array is usually done with the Fisher-Yates algorithm, for which you'll easily find JS implementations (it's easy to write anyway). A fast (theoretically not guaranteed to work with all future sort implementations) alternative is this one :
arr = arr.sort(function(a,b){ return Math.random()>0.5 });
The whole program
Your approach means to check over all the array in each step, looking if your random number is already inside the array, which means a lot lost time.
Best approach is disordering an ordered array. In each loop, we generate a random number (in the example, a number between 0 and 1) and with a 50% probability we change the item in the current position for other item in a random position (between 0 and the length of the array).
Hope it helps.
function disorder(arg) {
for (var i = 0; i < arg.length; i++) {
if (Math.random() < 0.5) {
var aux = arg[i];
var rndPos = Math.floor(Math.random()) * arg.length;
arg[i] = arg[rndPos];
arg[rndPos] = aux;
}
}
return arg;
}
var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var myNewArray = disorder(myArray);
myNewArray.forEach(function(item) {
console.log(item);
});