create array in reverse order - javascript

I've got buttons with a common class (buttons). How can I add their IDs in to an array in a reverse order?
var yourArray = [];
$('.buttons').each(function() {
yourArray.push( $(this).prop('id') );
});

You could create the array by adding each element to the beginning of the array using unshift():
var yourArray = [];
$('.buttons').each(function() {
yourArray.unshift(this.id);
});
Alternatively you can create it in the current order and then reverse() it. Also note that you can use map() to create the array initially:
var yourArray = $('.buttons').map(function() {
return this.id;
}).get().reverse();
Finally you can use this.id instead of creating a jQuery object just to access a property already accessible without the need of object creation.

You can do something simple with map() and reverse()
var yourArray = $('.buttons').map(function() {
return this.id; // get the id
})
.get() // get the array
.reverse(); // reverse the array
console.log(yourArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="a" class="buttons"></button>
<button id="b" class="buttons"></button>

Related

How to get value on class and put into array JavaScript DOM?

I have some tables that have data and can using it on <td>. So more like it I have something like this (show on images below)
My Element
I want to get that all positions Name and put it into an array so I can make of use that array I tried to use this code and got undefined
script.js
/** Checking if There positions name */
function checkPositions(){
let positions = document.getElementsByClassName('check-positions').innerHTML;
let array = [];
array.push(positions);
console.log(array);
}
Then how can I get that value??
The problem that you have is that document.getElementsByClassName('check-positions') returns a HTMLCollection which does not have an innerHTML property.
What you need to do is convert the HTMLCollection into an array, and then read the innerHTML property for each of the items in the array. See the following example:
const elements = document.getElementsByClassName('check-positions');
const positions = Array.from(elements).map(element => element.innerHTML);
console.log(positions);
<div class="check-positions">1</div>
<div class="check-positions">2</div>
<div class="check-positions">3</div>
Use like this
let positions = document.getElementsByClassName('check-positions')[0].innerHTML;
It's showing none because u r fatching whole array and pushing it without using indexes
Code
function checkPositions(){
all_ele = document.getElementsByClassName('check-positions')
length = all_ele.length
let array = [];
for( let i=0;i<length;i++)
{
let positions = document.getElementsByClassName('check-positions')[i].innerHTML;
array.push(positions);
}
console.log(array);
you can use jquery code to do this.
var arr = [];
$("#tablePlacement tr").each(function() {
var name = $(this).children('td.check-positions').text();
arr.push(name);
});
You should use
let positions = document.getElementsByClassName('check-positions').innerText;

Is it possible to break an "each" iteration, append or add something to one of the values and then continue?

Is it possible to break an "each" iteration, append or add something to one of the values and then continue?
var aKeys = new Array(),
aValues = new Array(),
sArray = {};
$(input).each(function (index, element) {
var sKey = $(this).attr('name'),
sValue = $(this).val();
aKeys.push(sKey);
aValues.push(sValue);
});
As you can see, I'm first creating a few arrays and an empty object named "sArray". Then I'm pushing the values inside those arrays via input attributes. Finally, I'm creating my object:
aKeys.forEach(function (v, j) {
sArray[v] = aValues[j];
});
return sArray;
But here's the thing. I want to add a nested object inside one of those values. I already have that object stored in another variable. Is there a way to append it or add it?
EDIT:
I've been looking at the examples and maybe I didn't express myself quite well. I've already created an object. What I wanna do is to append or store another object inside one of the keys of this object I've created.
sArray is an object, not an array. You don't need the arrays ata ll to build the object. Try this...
var sObj = {};
$("input").each(function (index, element) {
sObj[$(this).attr('name')] = $(this).val();
});
// Let's nest another object in there i guess...
var myObj = {"wut-wut": "in the butt"};
sObj.pickles = myObj;
console.log(sObj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name=one value=1>
<input name=two value=2>
<input name=three value=3>
<input name=four value=4>

Deleting an element in json array using Javascript

I want to delete the element from json array using nodejs. My json file match.json is as follows.
[{"id":"1234","time":"3"}]
from this I want to delete the first element so that the json file looks like this:
[]
I tried the following code,its printing an empty array in the console but it is not removing the elements from the match.json file
for(var i=0;i<w;i++)
{
for(var j=0;j<m;j++){
if((words[i].id==match[j].id) && (words[i].time==match[j].time))
{
var f1=0;
//var id1=match[j].id;
var linkadd=words[i].link;
delete match[j];
console.log(match);
}
}
}
Use match.splice(i, 1) instead of delete match[i]
var arr = JSON.parse(Match_json_data);
// remove 1st element
var indexOfItemToRemove = 0;
var noOfItemsToRemove = 1;
arr.splice(indexOfItemToRemove, noOfItemsToRemove);
Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice?v=control
This should work:
let myJsonString = '[{"id":"1234","time":"3"}]';
let myEditedJsonString = JSON.stringify(JSON.parse(myJsonString).shift());
to remove the element..you can use splice.. The element will be removed.
{
var f1=0;
//var id1=match[j].id;
var linkadd=words[i].link;
match.splice(i, 1);
console.log(match);
}
If you use delete match[i], the list becomes [undefined]. So use splice.
So basically delete does not delete the element, rather it sets the element as undefined.
const items = [{"id":"1234","time":"3"}]
console.log('before removing item ==> ', items)
items.splice(0 /*index to be removed*/, 1/*no. of items to be removed*/)
console.log('after removing item ==> ', items)
If you want to always take out the first element and update the array the use the following code.
var arr =[{"id":"1234","time":"3"}]
arr.reverse().pop()
If you want to get a subset of the array you can slice the array but it will not update the array but create a new array.
arr.slice(STARTING_ADDRESS,NO_OF_ELEMENTS_TO_SLICE)
NOTE: This will return a new array, So if you want to update the old array then you need to assign it to the old array.
arr = arr.slice(STARTING_ADDRESS,NO_OF_ELEMENTS_TO_SLICE)

Reference javascript array inside click function by dynamically creating the array name

So I have an array something like this:
var first_array = ['foo','bar','foobar'];
I am running a click function and trying to get the name of the array and loop through the array which has first as the ID name something like this
$('element').on('click',function(){
var id = $(this).attr('id');
var arr = id+"_array";
$.each(arr,function(index,value){
console.log(value);
})
})
Now the arr gives a variable name first_array and not the array. Hence the each loop fails. Is there a way to reference the array? I need to dynamically create the array variable name and get the array elements. I have also tried declaring the array globally and inside the click function but does not work.
Like Rayon Dabre said in the comments, you should use a parent object containing your first_array, and more, like that :
var parent_array = {
first_array: ['foo','bar','foobar'],
second_array: ['foo2', 'bar2', 'foobar2']
};
$('element').on('click',function(){
var id = $(this).attr('id');
var arr = parent_array[id+"_array"];
$.each(arr,function(index,value){
console.log(value);
})
});
You can put all your arrays into a javascript object or a parent array and access them by key/name like parentArr["first_array"]

Better way to create arrays in javascript?

I'm trying to create an array in Javascript with a size that is equivalent to the number of times a certain class is found in the DOM, and then iterate through it to grab the text from an input field present in that class. I can easily do this like so:
var count = 0;
$('.className').each(function() {
count++;
});
var classes = new Array(count);
count = 0;
$('.className input[type=text]').each(function() {
classes[count++] = $(this).val();
});
This looks like a lot of code for what seems to be a relatively simple task. Is there a more efficient or less lengthy way of doing this?
Thanks
It looks like you want this :
var classes = $('.className input[type=text]').map(function(){
return this.value
}).get();
But it's a guess : it's not clear why you start by counting all elements of the class and then iterate on the inputs.
You can construct an array of elements directly from your selector via the makeArray function, then transform the result using a map.
var classes = $.makeArray($('.className input[type=text]')).map(function() {
return $(this).val();
});
Use jQuery's map function, then get if you need a pure array:
var values = $('.className input[type=text]').map(function() {
return $(this).val();
}).get();
each passes the index, so you don't need to do it yourself:
var classes = [];
$('.className input[type=text]').each(function(index, value) {
classes[index] = $(this).val();
});
Arrays are dynamic and therefore don't need to be initialized. Create a new array, loop through the inputs and push the values to the new array:
var classes = [];
$('.className input[type=text]').each(function(idx, elem) {
classes.push($(elem).val());
});

Categories