How to remove an object from array using spilce? - javascript

I recently asked a question of (How to remove an element from array in javascript without making a new?).
b1 = document.getElementById('b1')
b2 = document.getElementById('b2')
myArray = [b1 , b2];
Now I have to use this array twice once i need choose random element from it and apply some properties on it and second i need to pop the element i have applied properties. Also its a long list of elements in array so i dont know their index numbers.
For better explanation
blocks = [document.getElementById("b1"),document.getElementById("b2"),document.getElementById("b3"),document.getElementById("b4"),document.getElementById("b5"),document.getElementById("b6"),document.getElementById("b7"),document.getElementById("b8"),document.getElementById("b9")]
//first use
function autoChance(){
const randomBlock = blocks[Math.floor(Math.random() * blocks.length)];
randomBlock.style.backgroundColor='blue';
}
//second use
function b1Click(){
b1.style.backgroundColor="red"
const index = blocks.indexOf('document.getElementById("b2")');
blocks.splice(index, 1);
console.log(blocks)
autoChance()
}
//If u see in console its removing the last item
.blocks{
width: 310px;
height: 304px;
overflow-wrap: normal;
background-color: aqua;
}
#b1,#b2,#b3,#b4,#b5,#b6,#b7,#b8,#b9{
width: 100px;
height: 100px;
position: relative;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="blocks">
<button id="b1" onclick="b1Click()"></button>
<button id="b2" onclick="b2Click()"></button>
<button id="b3" onclick="b3Click()"></button>
<button id="b4" onclick="b4Click()"></button>
<button id="b5" onclick="b5Click()"></button>
<button id="b6" onclick="b6Click()"></button>
<button id="b7" onclick="b7Click()"></button>
<button id="b8" onclick="b8Click()"></button>
<button id="b9" onclick="b9Click()"></button>
</div>
<script src="script.js"></script>
</body>
</html>

As I said in my comment on that other question, it doesn't matter what it is you're looking for, indexOf will find it if you pass the same thing into indexOf that's in the array; indexOf effectively does a === comparison.
Now, if you want to find the index of an object by checking its properties, or a string using a substring, or anything that isn't just a === comparison, you'd use findIndex with a callback (or find to find the object itself).
How can i remove them from array using the values...
The same way: splice with the index of the entry (if you want to keep the same array) or filter (if you want to create a new array).

Checkout this snippet. When you select elements using methods like getElementsByTagName, it may not return array. It might be an HTML collection or some object depending on the method you choose.
As you can see (in console), initially is an object. To change it to an array, see how I initialized elements, using [... ] Rest of the code is easy to understand. Let me know if you get stuck :)
var initially = document.getElementsByTagName('div')
console.log(typeof(initially));
var elements = [...initially];
console.log(elements);
var toSearch = document.querySelector('.four');
var ind = elements.indexOf(toSearch);
elements.splice(ind, 1);
console.log(elements);
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
<div class="four"></div>
<div class="five"></div>
<div class="six"></div>
<div class="seven"></div>

I would get a random number based on the length of your element array and then splice the array based on that number and return the value from that splice. That value will, however, be in an array so I will need to return the first index of that array.
var myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
function removeElement() {
let randomIndex = randomize(myArray.length);
let randomValueArr = myArray.splice(randomIndex, 1);
let randomValue = randomValueArr[0];
console.log(randomValue);
return randomValue;
}
function randomize(max, min = 0) {
return Math.floor(Math.random() * max + min)
}
<button onclick="removeElement()">Click me to remove elements</button>

Related

how to make strings in a an array turn into variables in js

i wanted to turn this strings in this array to variables so i could assign them to html elements:
let array = ['varOne', 'varTwo', 'varThree']
let array[0] = document.getElementById('id')
You almost certainly don't want to do this, but if you did here is how:
const names = ['varOne', 'varTwo', 'varThree']
names.forEach((variableName) => {
window[variableName] = document.getElementById(variableName)
})
console.log(varOne)
console.log(varTwo)
console.log(varThree)
<html>
<body>
<div id='varOne' />
<div id='varTwo' />
<div id='varThree' />
</body>
</html>

Declaring Javascript array within a function

Declaring an array within a function triggered by button causes the function to fail and not work as intended. What is the reason this happens? The "function C" block is having the problem.
I have also noticed that the ES6 syntax of "export ..." causes the entire thing to jam as well, it only accepts "module.export".
I am a total beginner, so I have no idea of what is going on.
This is my code:
<!-- Bootstrap CSS -->
<link href="resources/bootstrap.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="resources/custom2.css">
<link href="resources/TCJA's CSS.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
let TA = [0, 0, 0, 0]
function MF() {
TA = [0, document.getElementById("test1").value, document.getElementById("test2").value, document.getElementById("test3").value]
document.getElementById("shout1").innerHTML = TA[1]
document.getElementById("shout2").innerHTML = TA[2]
document.getElementById("shout3").innerHTML = document.getElementById("testCheck").checked
}
function C() {
var ACArray[0] = 2; //AttackerCard Array
var DCArray[0] = 1; //DefenderCard Array
var para = document.createElement("p");
var node = document.createTextNode("The attackers dealt " + document.getElementById("wand").value + " damage to the defenders.");
para.appendChild(node);
var element = document.getElementById("newElement");
element.appendChild(para);
}
</script>
</head>
<body>
<!-- Put code below -->
<br>
<label class="control-label">Tester Input</label>
<input class="form" id="test1">
<input class="form" id="test2">
<input class="form" id="test3">
<br>
<button id="doge" class="btn btn-primary" onclick="MF()"><h3>Result</h3></button>
<br>
<input id="testCheck" type="checkbox"> Check it?
<br>
<h2>Result:</h2>
<p id="shout1">Hello?</p>
<p id="shout2">Hello again?</p>
<p id="shout3">Hello a third time?</p>
<br>
<label class="control-label">Creator Input</label>
<input class="form" id="wand">
<button id="god" class="btn btn-success" onclick="C()"><h3>Create</h3></button>
<br>
<div id=newElement>
</div>
<button id="show">Show</button>
<!-- JQuery -->
<!-- End of body -->
</body>
</html>
What do you mean, by declaring var ACArray[0]=2;? Yes, it looks like declaring new array with first element equals 2, but, where is your array declaration?
The right way to do this: var ACArray = [2]; var DCArray = [1]; and so on.
Declare arrays Before assigning values into an array.
var ACArray = [];
var DCArray = [];
function C(){
ACArray[0] = 2;
DCArray[0] = 1;
}
The following syntax is incorrect:
var ACArray[0]=2; //AttackerCard Array
var DCArray[0]=1; //DefenderCard Array
The most convenient way to declare an array in JS is an Array literal like this:
var array = ['item1', 'item2'];
What we now have done is multiple steps in one. First we have created memory for an array using the var keyword and the array literal syntax.
Step 1:
var array = [];
Then we have initialized the array and put actual values inside the array like this:
Step 2
array[0] = 'item1';
array[1] = 'item2';
Important to understand is that you now can refer to all these elements in the following way:
console.log(array[0]); // logs item1
console.log(array[1]); // logs item2
And also be aware that the counting of the elements in the array starts with 0, not 1.

Storing return value in variable isn't giving me the same thing as calling the function by name

I'm working on a memory game using only vanilla javascript and the function below is supposed to store all open cards in an Nodelist, that I want to turn into an array later. When I call the function, using selected(); I get all of the cards I clicked on, but when I use the variable selectedCards, it only gives me the first card I clicked on. Why is that?
function selected () {
let select = [];
//class = 'open' turns the card over in grid when clicked
if (document.querySelectorAll('.open')) {
select.push((document.querySelectorAll('.open')));
};
return select;
};
let selectedCards = selected();
Eventually I want to use the function below to check if the cards in the selectedCards array match.
function isMatch() {
if (selectedCards[0].type === selectedCards[1].type) {
function matched(){
selectedCards[0].classList.add("match");
selectedCards[1].classList.add("match");
selectedCards[0].classList.remove("show", "open");
selectedCards[1].classList.remove("show", "open");
selectedCards = [];
}
}
};
I've only been learning javascript for around 2 weeks not, so this might now even be possible with the functions I've created? I dunno, any help is greatly appreciated though!
You can make the NodeList to Array like this.Here you can see both selected() and selectedCards returns the same result.
function selected () {
let select = [];
//class = 'open' turns the card over in grid when clicked
let sel = document.querySelector('.open');
if (sel) {
select= [].slice.call(sel.querySelectorAll('.inner'));
};
return select;
};
let selectedCards = selected();
console.log(selected());
console.log(selectedCards);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="open">
<div class="inner">
<div class="inner">
</div>
<div class="inner">
</div>
<div class="inner">
</div>
</div>
</div>
</body>
</html>

Check if an array o html elements have some of the following classes [duplicate]

This question already has answers here:
Finding matches between multiple JavaScript Arrays
(13 answers)
Closed 7 years ago.
// HTML
// Some Html content
<div class=​"class--1 common-class otherClass2">​…​</div>​
// Some Html content
<div class="otherdiv"></div>
<div class=​"common-class class--2">​…​</div>​
<div class=​"common-class class--3 otherClass">​…​</div>​
// Some Html content
i'm trying to iterate between 2 arrays;
one with className stored and the other with html elements targeted
// JAVASCRIPT
var arrayOfClasses = ["class--5", "class--10", "class--1", "class--2"];
var arrayOfElements = document.getElementsByClassName("common-class");
// This return the following array
// [<div class=​"common-class class--1">​…​</div>​, <div class=​"common-class class--2>​…​</div>​, <div class=​"common-class class--3>​…​</div>​];
How i get true value for the element with class--1 and class--2 and false for class--3 class--5 and class--10
I iterate throw the arrayOfElements[i].className
and after use the indexOf commented below
but found another problem here :S
"common-class class--10".indexOf("class--1")
// Return > 13 but i want -1 because is 10 no 1
Better without jQuery
Thanks in advance.
var array1 = ["Hello", 5, "Hola", 27, 'otherValue'];
var array2 = [27, "Hello"];
var intersection = [];
var intersectionObj = {};
for(var i=0; i<array1.length; i++) {
if(array2.indexOf(array1[i]) > -1) {
intersection.push(array1[i]);
}
}
alert(intersection);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
</body>
</html>

JavaScript getElementById returns null

I'm learning JavaScript and I'm wondering why something like:
document.getElementById('partofid'+variable+number) doesn't work?
Here are samples and JSfiddle link, I want "next" button to remove displayed item and show the next one.
HTML:
<div id="div-1"> 1 </div>
<div id="div-2" style="display: none"> 2 </div>
<div id="div-3" style="display: none"> 3 </div>
<div id="div-4" style="display: none"> 4 </div>
<a id="next" href="#">next</a>
JS:
var counter = 1;
var button = document.getElementById('next');
button.addEventListener("click",function(){
var currentDiv = document.getElementById('div-'+counter);
currentDiv.remove();
var nextDiv = document.getElementById('div-'+counter+1);
alert(nextDiv); // why does it return null
alert('div-'+counter+1); // while this doesn't?
nextQuestion.style.display = "block";
counter++;
},true);
Try using parseInt:
var nextDiv = document.getElementById('div-'+parseInt(counter+1,10));
The parseInt function converts its first argument to a string, parses it, and returns an integer.The second arguement is radix which is "base", as in a number system.
Demo
What's going on here is Javascript has some strange rules about types and the + operator.
string + anything means convert anything to string, then concatenate them together. So "foo" + "bar" == "foobar"... and "div" + 1 == "div1".
The the next step, addition is done left to right, so "div" + 1 + 1 goes to "div" + 1 == "div1".
"div1" + 1... remember, convert to string then put together, so we get "div1"+ 1 == "div11".
I would put parenthesis around your arithmetic. "div" + (1+1) would do the right hand side thing first, so (1+1) == 2 as you expect, then "div" + 2 == "div2", so that's what you expect.
As to the alert thing, your first one is looking at the result of the element lookup, and the second one is looking at the string itself. So the first is null because the element lookup didn't find anything.
This code results in string concatenation. E.g. if counter is 1, then you will get div-11
'div-'+counter+1
This is because addition is resolved from right to left.
Then you try to retrieve element with id div-11, but you don't have html element with such an id. That's why the function getElementById returns null.
To solve the problem first add counter to 1 and then join it with div, like this 'div-'+(counter+1)
Because counter+1 = 11 => id = div-11 is not exist. Try this:
var counter = 1;
var button = document.getElementById('next');
button.addEventListener("click",function(){
var currentDiv = document.getElementById('div-'+counter);
currentDiv.remove();
var nextDiv = document.getElementById('div-'+Number(counter+1));
alert(nextDiv); // why does it return null
alert('div-'+Number(counter+1)); // while this doesn't?
nextQuestion.style.display = "block";
counter++;
},true);
it does work and does exactly what you asked it to do but since you do not have a div-11 there is nothing found so the evaluation returns null.
if you want div-2 then simply use order of operations to sum the counter to the number:
Fiddle
Here is your answer:
<html>
<head>
<script>
function load()
{
var counter = 1;
var button = document.getElementById('next');
button.addEventListener("click",function(){
var currentDiv = document.getElementById('div-'+counter);
currentDiv.remove();
var nextDiv = document.getElementById('div-'+(counter+1));
//alert(nextDiv); // why does it return null
//alert('div-'+(counter+1)); // while this doesn't?
nextDiv.style.display = "block";
counter++;
},true);
}
</script>
</head>
<body onload="load()">
<div id="div-1"> 1 </div>
<div id="div-2" style="display: none"> 2 </div>
<div id="div-3" style="display: none"> 3 </div>
<div id="div-4" style="display: none"> 4 </div>
<a id="next" href="#">next</a>
</body>
<html>
To solve this kind of returning "null" values by getElementById("").
you can use script inside the body instead of head it will return the html element.
const m=document.getElementById('one')
const m1=document.getElementById('demo')
console.log(m1);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="demo">sample text</p>
<script src="script.js"></script>
</body>
</html>

Categories