I have a bunch of arrays, eg:
var myArrayName = [1, 2, 3, 4, 5, 6];
var myArrayName2 = [1, 2, 3, 4, 5, 6];
var myArrayName3 = [1, 2, 3, 4, 5, 6];
In my DOM I have elements with data-name="myArrayName" data-push="7", data-name="myArrayName2" data-push="2" etc.
I want to select all the elements with data-name and then push data-push values to them, so:
$("*[data-name]").each(function(){
var arName = $(this).data("name");
var toPush = $(this).data("push");
// how do I make the stuff below work?
// arName.push(toPush);
})
This would select all the elements with the attribute data-name
var arrDataAttr = new Array();
var arrDataPush = new Array();
$(document).find("[data-attr]").each(function()
{
arrDataAttr.push($(this).attr("data-attr"));
arrDataPush.push($(this).attr("data-push"));
});
You need to use an object ( dictionary, map, whatever you call it ):
var arrays = {
'myArrayName': [],
'myArrayName2':[],
'myArrayName3':[]
}
$("*[data-name]").each(function(){
var arName = $(this).data("name");
var toPush = $(this).data("push");
arrays[arName].push(toPush);
})
An easy way to do this could be to wrap all the arrays under an object to namespace them:
var arrays = {
myArrayName: [1, 2, 3, 4, 5, 6];
myArrayName2: [1, 2, 3, 4, 5, 6];
myArrayName3: [1, 2, 3, 4, 5, 6];
};
Then, you can access the arrays by their name, like this:
// to access the first array:
arrays["myArrayName"];
The final code looks like this:
$("[data-name]").each(function(){
var $item = $(this);
var arName = $item.data("name");
var toPush = $item.data("push");
arrays[arName].push(toPush);
});
Notes:
Please note that I'm caching the $(this) variable, if you want to know why, check this
If you want to know more about accessing object properties with JavaScript, check this
Try adjusting names of array variables , data-* attribute , using $.each() called on arrays , select element having data-name ending with current index of loop
var myArrayName0 = [1, 2, 3, 4, 5, 6];
var myArrayName1 = [1, 2, 3, 4, 5, 6];
var myArrayName2 = [1, 2, 3, 4, 5, 6];
$.each([myArrayName0, myArrayName1, myArrayName2], function(index, arr) {
arr.push($("[data-name$=" + index + "]").data("push"))
});
console.log(myArrayName0, myArrayName1, myArrayName2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div data-name="myArrayName0" data-push="7"></div>
<div data-name="myArrayName1" data-push="2"></div>
<div data-name="myArrayName2" data-push="1"></div>
Related
I have a java script OOP pattern as follows: a main object (Team) has other objects (Players) as properties. A functional mixin exists for both Team and Player objects to keep methods. New instances of both objects are created using constructor functions, with Player objects passed into Team objects as parameters. The mixins then call the objects to allow methods to be available (an approach described more fully here:
https://javascriptweblog.wordpress.com/2011/05/31/a-fresh-look-at-javascript-mixins/.
Now, the properties of the new Players are arrays of numbers. If i "hard code" the numbers in as i create the new Players, everthing works and the methods can be used on the objects. However, i wish to make the data selections more dynamic (e.g. the values in the array may change based on menu selections or such). For this reason i would like to keep the data array stored in a variable, and then pass that variable into the new Player constructor sequence and still maintain the mixin functionality. Unfortunately simply substituting in the variable name, either as is, or as [] notation, breaks the functionality and results in no results or NaN results for the console.log requests..
Can anybody help on making this step...
code with descriptive comments as follows:
// Mixin for Team methods...
var asTeam = function() {
this.ability1 = function() {
var ab = (this.p1.p4arr[4] + this.p2.p5arr[2]);
return ab;
};
return this;
};
// Mixin for Player Methods..The methods use calculations of different values within the property arrays..
var asPlayer = function() {
this.skill1 = function() {
var a = this.p4arr[0] + this.p5arr[0];
return a;
};
this.skill2 = function() {
var a = this.p5arr[2] * this.p6arr[3] / this.p4arr[4];
return a;
};
return this;
};
// constructor function for Teams..
var Team = function(p1, p2, p3) {
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
};
// constructor function for Players..
var Player = function(p4arr, p5arr, p6arr) {
this.p4arr = p4arr;
this.p5arr = p5arr;
this.p6arr = p6arr;
};
// call the object prototypes from Mixins..
asTeam.call(Team.prototype);
asPlayer.call(Player.prototype);
// create a new Players..
// If used, this code works...
//var john = new Player([3,7,9,4,1,6],[2,16,3,5,1,1],[24,6,3,21,5,3]);
//var bob = new Player([2,2,1,3,4,1],[3,8,6,2,1,4],[6,4,8,6,2,5]);
//var ian = new Player([3,8,3,2,5,4],[2,7,4,3,7,3],[7,4,8,5,3,2]);
// Instead want to use this code or something similar that works to pick up the data arrays from the variables at the bottom ...
var john = new Player(arr1, arr2, arr3);
var bob = new Player(arr4, arr5, arr6);
var ian = new Player(arr7, arr8, arr9);
//or (doesnt work either)
// var john = new Player([arr1],[arr2],[arr3]);
//etc..
// create a new Team
var Team1 = new Team(john, bob, ian);
console.log(Team1.ability1());
console.log(john.skill2());
console.log(bob.skill1());
console.log(john.p4arr);
// data arrays stored in variables..
var arr1 = [3, 7, 9, 4, 1, 6];
var arr2 = [2, 16, 3, 5, 1, 1];
var arr3 = [24, 6, 3, 21, 5, 3];
var arr4 = [2, 2, 1, 3, 4, 1];
var arr5 = [3, 8, 6, 2, 1, 4];
var arr6 = [6, 4, 8, 6, 2, 5];
var arr7 = [3, 8, 3, 2, 5, 4];
var arr8 = [2, 7, 4, 3, 7, 3];
var arr9 = [7, 4, 8, 5, 3, 2];
You're calling the constructor before you initialize the variables, so you're passing undefined values to the constructor. Simply change the order of the code:
// data arrays stored in variables..
var arr1 = [3, 7, 9, 4, 1, 6];
var arr2 = [2, 16, 3, 5, 1, 1];
var arr3 = [24, 6, 3, 21, 5, 3];
var arr4 = [2, 2, 1, 3, 4, 1];
var arr5 = [3, 8, 6, 2, 1, 4];
var arr6 = [6, 4, 8, 6, 2, 5];
var arr7 = [3, 8, 3, 2, 5, 4];
var arr8 = [2, 7, 4, 3, 7, 3];
var arr9 = [7, 4, 8, 5, 3, 2];
var john = new Player(arr1, arr2, arr3);
var bob = new Player(arr4, arr5, arr6);
var ian = new Player(arr7, arr8, arr9);
// create a new Team
var Team1 = new Team(john, bob, ian);
console.log(Team1.ability1());
console.log(john.skill2());
console.log(bob.skill1());
console.log(john.p4arr);
I have the following function which is supposed to remove the smallest value from an array, but if this is a duplicate it will just remove the first one and leave the others.
var array1 = [1, 2, 3, 4, 5];
var array2 = [5, 3, 2, 1, 4];
var array3 = [2, 2, 1, 2, 1];
function removeSmallest(numbers) {
return numbers.filter(function(elem, pos, self) {
if(elem == Math.min.apply(null, numbers) && pos == self.indexOf(elem)) {
// Remove element from Array
console.log(elem, pos);
numbers.splice(pos, 1);
};
return numbers;
});
};
Via console.log(elem, pos) I understand that I have correctly identified the smallest and first element in the array, but when I try to remove it through splice(), I end up getting the following result for the arrays:
array1 = [1, 3, 4, 5]; // But I expected [2, 3, 4, 5]
array2 = [5, 3, 2, 1]; // But I expected [5, 3, 2, 4]
array3 = [2, 2, 1, 1]; // But I expected [2, 2, 2, 1]
Do you know what is the issue with my code? Thanks in advance for your replies!
function removeSmallest(numbers) {
const smallest = Math.min.apply(null, numbers);
const pos = numbers.indexOf(smallest);
return numbers.slice(0, pos).concat(numbers.slice(pos + 1));
};
You shouldn't use filter() the way you do. It's also a good practice that a function should return a new array rather than modifying the existing one and you definitely shouldn't modify an array while iterating over it.
function removeSmallest(arr){
var temp=arr.slice(),smallElement=null;
temp.sort(sortReverse);
smallElement=temp[temp.length-1];
var position=arr.indexOf(smallElement);
arr.splice(pos,1);
console.log(arr);
}
function sortReverse (a,b){
if(a<b){return 1}
else if(a>b){return -1;}
else{return 0;}
}
var array1 = [1, 2, 3, 4, 5];
removeSmallest(array1);
Basic question on .splice() method, and how best to remove an element from an array.
I want to remove an item from an array with .splice() but when I do, I want to have the original array minus the removed element returned. .splice() returns the removed element instead.
var arr = [1, 2, 3, 4, 5, 6, 7]
var newArr = arr.splice(3, 1)
console.log(newArr) // [4]
// whereas I want [1, 2, 3, 5, 6, 7]
What's the best, and most eloquent way to do this?
Using the spread operator, you can do:
var arr = [1,2,3,4,5,6],
indexToRemove = 3,
newArr = [
...arr.slice(0,indexToRemove),
...arr.slice(indexToRemove+1)
]
Or if you want to use ES5, it can look something like:
var arr = [1,2,3,4,5,6],
indexToRemove = 3,
newArr = [].concat(arr.slice(0,indexToRemove)).concat(arr.slice(indexToRemove+1))
.splice mutates the array in place and returns the removed elements. So unless you actually need a function that returns the array itself, just access arr:
var arr = [1, 2, 3, 4, 5, 6, 7]
arr.splice(3, 1)
console.log(arr) // [1, 2, 3, 5, 6, 7]
You can create a wrapper function that performs the splice and returns the array:
function remove(arr, index) {
arr.splice(index, 1)
return arr;
}
var newArr = remove(arr, 3);
// Note: `newArr` is not a new array, it has the same value as `arr`
If you want to create a new array, without mutating the original array, you could use .filter:
var newArr = arr.filter(function(element, index) {
return index !== 3;
}); // [1, 2, 3, 5, 6, 7]
arr; // [1, 2, 3, 4, 5, 6, 7]
I need to check if all items in an array can be found within another array. That is, I need to check if one array is a subset of another array.
Example:
var array = [1, 2, 5, 7];
var otherArray = [1, 2, 3, 4, 5, 6, 7, 8];
Comparing these two arrays above should return true as all items in array can be found in otherArray.
var array = [1, 2, 7, 9];
var otherArray = [1, 2, 3, 4, 5, 6, 7, 8];
Comparing these two arrays above should return false as one of the items in array cannot be found in otherArray.
I have tried to use the indexOf method inside a for loop without success.
I hope someone could help me. :)
Use Array.prototype.every:
The every() method tests whether all elements in the array pass the test implemented by the provided function.
var array = [1, 2, 7, 9];
var otherArray = [1, 2, 3, 4, 5, 6, 7, 8];
var isSubset = array.every(function(val) {
return otherArray.indexOf(val) >= 0;
})
document.body.innerHTML = "Is array a subset of otherArray? " + isSubset;
When I want to remove one element, it is easy. This is my function:
function removeValues(array, value) {
for(var i=0; i<array.length; i++) {
if(array[i] == value) {
array.splice(i, 1);
break;
}
}
return array;
}
But how do I remove multiple elements?
Here a simple version using ES7:
// removing values
let items = [1, 2, 3, 4];
let valuesToRemove = [1, 3, 4]
items = items.filter((i) => !valuesToRemove.includes(i))
For a simple version for ES6
// removing values
let items =[1, 2, 3, 4];
let valuesToRemove = [1, 3, 4]
items = items.filter((i) => (valuesToRemove.indexOf(i) === -1))
const items = [0, 1, 2, 3, 4];
[1, 4, 3].reverse().forEach((index) => {
items.splice(index, 1)
})
// [0, 2, 4]
I believe you will find the kind of functionality you are looking for in Javascript's built in array functions... particularily Array.map(); and Array.filter();
//Array Filter
function isBigEnough(value) {
return value >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
//Array Map (Can also be used to filter)
var numbers = [1, 4, 9];
var doubles = numbers.map(function(num) {
return num * 2;
});
// doubles is now [2, 8, 18]. numbers is still [1, 4, 9]
/////UPDATE REFLECTING REMOVAL OF VALUES USING ARRAY MAP
var a = [1,2,3,4,5,6];
a.map(function(v,i){
if(v%2==0){
a.pop(i);
}
});
console.log(a);
// as shown above all array functions can be used within the call back to filter the original array. Alternativelty another array could be populated within the function and then aassigned to the variable a effectivley reducing the array.