I have the following code:
var foo = 'foo'
var bar = 'bar'
var arr = [1,2,3]
I want to add to foo several times at the beginning of the array and bar at the end of the array. The number of times each element added should be dynamic and the resulting array should be something like:
['foo','foo',1,2,3,'bar',bar','bar']
Is there a better method than using a loop for each element?I could use lodash if needed.
If better means shorter, yes there's a way:
var foo = 'foo';
var bar = 'bar'
var arr = [1,2,3]
var result = [
...Array(2).fill(foo),
...arr,
...Array(3).fill(bar)
];
Or something like this.
var foo = Array.from({length:2}, v => 'foo');
var bar = Array.from({length:3}, v => 'bar');
var arr = [1,2,3]
arr.push(...bar);
arr.unshift(...foo);
console.log(arr);
Try this forloop method. Array#unshift() added the value on starting of array.push add with end of the array
var foo = 'foo'
var bar = 'bar'
var arr = [1,2,3]
for(var i=0; i<(Math.random() * 5); i++){
arr.unshift(foo)
}
for(var i=0; i<(Math.random() * 5); i++){
arr.push(bar)
}
console.log(arr)
You can use unshift and push like
function pushToBeginning(arr, str, count){
while(count--){
arr.unshift(str);
}
}
function pushToEnd(arr, str, count){
while(count--){
arr.push(str);
}
}
let arr = [1, 2, 3];
pushToBeginning(arr, 'Foo', 3);
pushToEnd(arr, 'Bar', 2);
console.log(arr);
Related
My goal is to create an array like this:
[{"str":"a","number":1},{"str":"a","number":2},{"str":"b","number":1},{"str":"b","number":2}]
so I wrote this javascript
abc = ["a","b"]
num = [1,2]
arr = []
a = {}
for (var i in abc)
{
str = abc[i]
a.str = str;
for(var x in num)
{
number = num[x]
a.number = number
console.log(a)
arr.push(a)
}
}
the console log looks fine, but the array looks like this:
[{"str":"b","number":2},{"str":"b","number":2},{"str":"b","number":2},{"str":"b","number":2}]
Can anyone could explain this?
This is happening because you are actually working with a reference to the same object, thus modifying the same over and over.
To fix it you must declare a new object in every iteration you want to use a different one.
Try something like this:
var abc = ["a", "b"];
var num = [1, 2];
var arr = [];
for (var i in abc) {
for (var x in num) {
var a = {};
a.str = abc[i];
a.number = num[x];
arr.push(a);
}
}
console.log(arr);
Also, don't forget to declare your variables with var or let and end your statements with ;.
As said in the comments, you’ve pushed your a object to arr many times, instead of adding four separate objects. To fix this issue, you could declare a in the for (var x in num) loop, every time as a new object (using const or let). But I’ve simplified it further, see the code below.
To iterate through JavaScript arrays, you should use .forEach method.
let abc = ['a', 'b'];
let num = [1, 2];
let arr = [];
abc.forEach(letter => {
num.forEach(number => {
arr.push({number: number, str: letter});
});
});
abc = ["a","b"]
num = [1,2]
arr = []
for (var i in abc)
{
for(var x in num)
{
a = {} ---------------- Reset "a"
str = abc[i] --------------------- 1
a.str = str; --------------------- 2
number = num[x]
a.number = number
console.log(a)
arr.push(a)
}
}
console.log(arr)
// Move 1 and 2 inside the second loop
Using map :
let tempArray = abc.map((e,i) => { return num.map((ee,ii) => { return {"str": e, "number": ee }; } ) });
$.merge(tempArray[0], tempArray[1]);
If I have an array like [1,2,3,4], and I want to duplicate and reverse it, how do I get it to return [1,2,3,4,4,3,2,1]?
Array.prototype.duplicateAndReverse = function() {
const initial = this;
const reversed = initial.reverse();
return initial.concat(reversed);
}
What am i doing wrong here? It returns [4,3,2,1,4,3,2,1]
Try this:
Array.prototype.duplicateAndReverse = function() {
const initial = this;
const reversed = initial.slice().reverse();
return initial.concat(reversed);
}
var myArray = [1,2,3,4];
alert(myArray.duplicateAndReverse());
Your code is reversing initial as well as setting reversed to the result, so you have two identical (reversed) arrays. Instead, use .slice() to duplicate the initial array, and reverse that instead.
var arr = [1,2,3,4];
for(var len = arr.length; len; len--)
arr.push(arr[len - 1]);
console.log(arr);
I don't recommend you mess with Array.prototype but here is what you want:
Array.prototype.duplicateAndReverse = function() {
let res = this.slice(); // create another copy so the original array will stay intact
for(var len = res.length; len; len--)
res.push(res[len - 1]);
return res;
}
let arr = [1, 2, 3, 4];
console.log(arr.duplicateAndReverse());
The problem was that you tried to reverse the initial array in place.Use the following optimized solution:
Array.prototype.duplicateAndReverse = function() {
return this.concat(this.slice().reverse());
}
console.log([1,2,3,4].duplicateAndReverse());
To retain the original array and create its reversed copy use Array.prototype.slice() function combined with Array.prototype.reverse() function
This is your problem because reverse() also reverse the original array
arr
var arr = [1,2,3,4]
var dup = arr.reverse()
console.log(arr) // => [4, 3, 2, 1]
console.log(dup) // => [4, 3, 2, 1]
You need to clone the original array first
var dup = arr.slice().reverse()
And then you can concat the 2 arrays to get the result. Happy coding!
Oriental solution, hihi.
var arr = [1,2,3,4];
var newArr = [];
arr.forEach((_,i) => newArr.unshift(arr[arr.length-i-1]) && newArr.push(arr[arr.length-i-1]))
console.log(newArr);
I have key value pairs like :
var x={1:Car,
2: Cycle,
3:John
}
This is response coming from JSON.[Object object]
I have array like :var arr=[1,3,2]
I want to sort x as per arr .
order should be : {1:Car,3:John,2:Cycle}
In javascript how to achieve this.
You don't need to sort them, just make a new empty array and populate it by getting the values of arr and using them as the index of x.
var x = {
1: 'Car',
2: 'Cycle',
3: 'John'
};
var arr = [1, 3, 2];
var output = [];
arr.forEach(function(item){
output.push(x[item]);
});
console.log(output);
Fiddle.
var order = function(obj, arr) {
var temp = {};
for (var i = 0; i < arr.length; i++) {
temp[i] = obj[arr[i]];
}
return temp;
}
var x = {
1: "Car",
2: "Cycle",
3: "John"
}
var arr = [1, 3, 2]
x = order(x, arr);
console.log(x);
i have this variable below,
var arr = {
lines: 1,
angle: 2
};
how would i append / push this into my arr variable?
var arr2 = { hi : 3 }
I've tried push() and just simply adding the two. but failed
var r = arr+''+arr2;
alert(r.toSource());
the alert gives me this
(new String("[object Object][object Object]"))
you can add a new property in a static way, like this:
arr.hi = 3;
but if you want to add all the properties from another object (a merge of object's properties) here a simple snippet:
var arr = {
lines: 1,
angle: 2
};
alert(JSON.stringify(arr));
var arr2 = {
hi : 3,
jsIs: "aWeSoMe"
};
//add all the key/value pairs of arr2 to arr
Object.keys(arr2).forEach(function (key) {
arr[key] = arr2[key];
});
alert(JSON.stringify(arr));
You can assign that into arr variable using
// if you want to enter object itself
arr.arr2 = arr2;
// if you want to remove arr2
delete arr2
// if you want to include just hi
arr.hi = arr2.hi;
// if you want to remove hi from arr2
delete arr2.hi
I have two arrays
var a= $("#update-select1").val(); // gives value 1,2,4
var b= $("#update-select2").val(); // 1,2,5
I want two different arrays from the above two arrays.
//array has the values which is in `b` but not in `a`
var c = [5]
//another array has value in `a` but not in `b`
var d =[4]
You can use Array.filter this way:
var c = [1,2,5]
.filter(function(a){return this.indexOf(a) === -1},[1,2,4]); //=> [5]
var d = [1,2,4]
.filter(function(a){return this.indexOf(a) === -1},[1,2,5]); //=> [4]
Or:
function notIn(a){
return this.indexOf(a) === -1;
}
var a = [1,2,4]
,b = [1,2,5]
,c = b.filter(notIn,a)
,d = a.filter(notIn,b);
See also
You can try the grep() method
var a1 = [1, 2, 4];
var a2 = [1, 2, 5];
var difference = $.grep(a1, function (x) {
return $.inArray(x, a2) < 0
});
alert(" the difference is " + difference);
JSFiddle
I know this is an old question, but I thought I would share this
little trick.
var diff = $(old_array).not(new_array).get();
diff now contains what was in old_array that is not in new_array
Found this on Compare 2 arrays which returns difference
try something like this
var a= [1,2,4];
var b= [1,2,5];
var c = [];
jQuery.each(b,function(k,v){
if(a.indexOf(v) < 0){
c.push(v);
}
})
console.log(c);//[5]
var d = [];
jQuery.each(a,function(k,v){
if(b.indexOf(v) < 0){
d.push(v);
}
})
console.log(d);//[4]