How to store each value into one array? - javascript

Hi all I have problem to make some id into one array
Maybe you can help me...This image is the result
enter image description here
and this is my code
$.each(data.rows, function (i, ele) {
var tes = ele.ID;
console.log('ItemID', tes);
}
The Result that i want expect is each item in the one array like this 'ItemID = [22,2,43,2]'

const idArray = data.rows.map((r)=>r.ID)
//More verbose
const idArray = data.rows.map(function (ele){
return r.ID;
});
Map creates a loop through all the values in the array and uses the return of the function passed to create a new array.
EDIT:
I'm not sure I understand, you'd want an array of array?
const idArray = data.rows.map(function (ele){
return [r.ID];
});

var tempArray = []
$.each(data.rows, function (i, ele) {
tempArray.push(ele.ID);
}
// tempArray will be the solution

var data = [1,2,3,4]; // Assuming this array contains rows data
var resultArray = []; // Result array
var ids = data.map(function (ele){
return ele;
});
resultArray.push(ids.join(',')); // Join ids using "," separator
console.log(resultArray); // ["1,2,3,4"]

Related

How to store values in an array Jquery?

I have a function:
chatManager.connect()
.then(currentUser => {
var final = currentUser.users;
var name = [];
var arr = [];
$.each(final,function(index,val){
if(val.name != '{{Auth::user()->name}}')
{
console.log(val.id); //Harry, Ron (each in different line)
arr = name.push(val.id)
console.log(arr); //1,2 (each in different line)
var presence = val.presenceStore.store.{{Auth::user()->name}}{{Auth::user()->id}}
}
});
I want the arr to be an array like [Harry,Ron]. Why is it not working? I am new to Jquery. Please help.
arr = name.push(val.id) is your problem. push returns the array's new length, not an array. Simply replace the line with
arr.push(val.id);

jQuery move value to last position

I have the object as,
var names =["LET_ABC","PET_DEF","Num_123","Num_456","SET_GHI","RET_JKL"];
Now i have to move the value which contains "Num" to the last which means after the "Num" value there should be no values.
This is how i add the value to the array,
result.each(function () {
var tempObject = {},
attributes = $(this).data();
names.push(attributes.prefix+ '_' + attributes.value)
});
Can i somehow manipulate the above code to make the "Num" values move at last.
I need something like,
var names =["LET_ABC","PET_DEF","SET_GHI","RET_JKL","Num_123","Num_456"];
for(var i=0;i<names.length;i++){
if(names[i].match("^Num")){
names.push(names.splice(i, 1)[0]);
}
}
Working example (with explanation in comments):-
var names =["LET_ABC","LET_DEF","Num_123","Num_456","LET_GHI","LET_JKL"];//your array
function movetoLast(names,checkword){// function with array and checking prefix
$(names).each(function(index,value){ // iterate over array
if(value.indexOf(checkword) >= 0){ // check value have that prefix or not in it
names.push(names.splice(names.indexOf(value), 1)[0]); // if yes move that value to last in array
}
});
return names; // return modified array
}
var names = movetoLast(names,"Num");// call function
console.log(names); // print modified array in console
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this.simple use Array#filter and Array#concat
var names = ["LET_ABC", "PET_DEF", "Num_123", "Num_456", "SET_GHI", "RET_JKL"];
console.log(names.filter(a => !a.match(/(\d+)/g)).concat(names.filter(a => a.match(/(\d+)/g))))
I would put the numbers in a separate array to concatenate the two arrays at the end.
result.each(function () {
var tempObject = {}, attributes = $(this).data();
var numsArray = [];
if (attributes.prefix==Num){
numsArray.push(attributes.prefix+ '_' + attributes.value);
}else{
names.push(attributes.prefix+ '_' + attributes.value)
}
names.concat(numsArray);
});
Use push to add a value to the end of an array if it has the "Num" prefix and use unshift to add a value to the beginning of an array if it does not have the "Num" prefix. Working code:
var names =["LET_ABC","PET_DEF","Num_123","Num_456","SET_GHI","RET_JKL"];
$(document).ready(function(){
result_array = [];
$.each(names, function(index, value){
if (value.substring(0,3)=="Num"){
result_array.push(value);
} else{
result_array.unshift(value);
};
});
console.log(result_array);
});

Array in Array : How to store array data in an array

For example I have brunch of data like below:
HTML:
<p class="test-tag">abc+dd</p><p class="test-tag">gf+sx</p>
and store in JavaScript in array form
var text = ["abc+dd","gf+sx"];
And I must return an array like below:
var res = [["abc", "dd"],["gf", "sx"]];
What's the best way to do this?
Something like below should work..
var finalArr = [];
$('.test-tag').each (function (){
var value = $(this).text;
var subArr = value. map(function (b){
return b.split('+');
})
finalArr. push(subArr);
})
You can map over your array and use split:
Example JSBin
var text = ["abc+dd","gf+sx"];
var array = text.map(function(v) {
return v.split('+');
});

Add field to a new JavaScript array copy

I have a JavaScript array which has the follow structure:
[{id:'id1', container:'3', routing:'4'},{id:'id2', container:'2', routing:'5'},..]
Now through the command 'push' i was able to make a copy of this array. My question is how to add a new element (NEWFIELD) to the new array, to become like this:
[{id:'id1', container:'3', routing:'4',NEWFIELD:'X'},{id:'id2', container:'2', routing:'5',NEWFIELD:'Y'},..]
You can try something like following
var arr = [{id:'id1', container:'3', routing:'4'},{id:'id2', container:'2', routing:'5'},..];
var new_arr = arr.map(function(item){
var clone = Object.assign({}, item); // Objects are pass by referenced, hence, you need to clone object
clone.NEWFIELD = clone.routing/clone.container;
return clone;
});
var arr = [{id:'id1', container:'3', routing:'4'},{id:'id2', container:'2', routing:'5'}];
// clone an array
var newArr = arr.map(function(e) {
return JSON.parse(JSON.stringify(e));
});
// add new field
newArr.forEach(function(e) {
e['NEWFIELD'] = e.routing / e.container;
});
console.log(arr);
console.log(newArr);

Return Object in Array if Property Match

Here is the scenario:
There is a parameter titledlistOfSelectedProductIdsthat contains
all of the selected ids.
There is another list titled listOfAllPossibleProducts, which
contains a list of objects. That object contains a ProductId,
ProductName, and ProductCode. It looks something like this:
The task at hand:
I need to loop through my listOfSelectedProductIds. If the ProductId matches a ProductId from listOfAllPossibleProducts, then I need to return that object.
Here is what I am doing:
function SelectedProducts(listOfSelectedProductIds){
for (var index = 0; index < listOfSelectedProductIds.length; index++) {
var currentItem = listOfSelectedProductIds[index];
var desiredProduct = _.contains(listOfAllPossibleProducts, currentItem);
if (desiredProduct === true) {
return listOfAllPossibleProducts[index];
}
}
}
What's currently happening:
My loop is getting the selected id as expected i.e. currentItem, but _.contains(...)
always returns false.
Question:
What is the best way to find the objects in
listOfAllPossibleProducts that have ProductIds that match my
ProductIds in the listOfSelectedProductIds
How about using _.filter:
var result = _.filter(listOfAllPossibleProducts, function (el) {
return _.contains(listOfSelectedProductIds, el.id);
});
Or the non-underscore method:
var result = listOfAllPossibleProducts.filter(function (el) {
return listOfSelectedProductIds.indexOf(el.id) > -1;
});
DEMO
create another structure productsByProductId once!
var productsByProductId = {};
listOfAllPossibleProducts.forEach(p => {
productsByProductId[p.ProductId()] = p
});
and maybe a helper function
function getProductById(id){
return productsByProductId[id];
}
and use this to map the ids to the nodes
var selectedProducts = listOfSelectedProductIds.map(getProductById)

Categories