Add to Array jQuery - javascript

I know how to initliaize one but how do add I items to an Array? I heard it was push() maybe? I can't find it...

For JavaScript arrays, you use push().
var a = [];
a.push(12);
a.push(32);
For jQuery objects, there's add().
$('div.test').add('p.blue');
Note that while push() modifies the original array in-place, add() returns a new jQuery object, it does not modify the original one.

push is a native javascript method. You could use it like this:
var array = [1, 2, 3];
array.push(4); // array now is [1, 2, 3, 4]
array.push(5, 6, 7); // array now is [1, 2, 3, 4, 5, 6, 7]

You are right. This has nothing to do with jQuery though.
var myArray = [];
myArray.push("foo");
// myArray now contains "foo" at index 0.

For JavaScript arrays, you use Both push() and concat() function.
var array = [1, 2, 3];
array.push(4, 5); //use push for appending a single array.
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
var array3 = array1.concat(array2); //It is better use concat for appending more then one array.

just it jquery
var linkModel = {
Link: "",
Url: "",
Summary: "",
};
var model = [];
for (let i = 1; i < 2; i++) {
linkModel.Link = "Test.com" + i;
linkModel.Url= "www.Test.com" + i;
linkModel.Summary= "Test is add" + i;
model.Links.push(linkModel);
}

Related

Perform unshift method on a copy of array

I want to unshift on a copy of the array, but the original array modifies too. Why is that?
var array1 = [1, 2, 3]
var array2 = array1
array2.unshift(4, 5)
console.log(array1)
console.log(array2)
Try using Array.from()
var array1 = [1, 2, 3]
var array2 = Array.from(array1)
array2.unshift(4, 5)
console.log(array1)
console.log(array2)
Use spread operator( ... ) to make second array. It will make a new array with new reference. And then perform your task.
var array1 = [1, 2, 3];
var array2 = [...array1];
array2.unshift(4, 5);
console.log(array1);
console.log(array2);

How to push array into another array as one element

I'm new in JS, can't find solution to do something like that
var arr = [0];
var elem = [1, 2, 3];
???
console.log(arr); // shows [0, [1, 2, 3]];
I've tried with .push(elem), JS decides that I passed array of values (not a single one), and concatenate content of arr and elem arrays, so that the result is [0, 1, 2, 3]
Use concat!
var arr = [0];
var elem = [1, 2, 3];
var newArr = arr.concat([elem]);
console.log(newArr); // => [0,[1,2,3]]
You may try to use spread operator to concatenate values of an array.
For example:
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5];
console.log(arr2);
//Output: [ 1, 2, 3, 4, 5 ]
Now, after you wrote, what you want,
[0, [1, 2, 3]]
you could use at lease three different approaches:
Simple assignment at the end of the array
var arr = [0],
elem = [1, 2, 3];
arr[arr.length] = elem;
console.log(arr);
Array#push for pushing a value/object at the end of an array, which is basically the same as above without indicating the place for inserting, but you can use more item for pusing to the array.
var arr = [0],
elem = [1, 2, 3];
arr.push(elem);
console.log(arr);
Array#concat, creating a new array with with the given array and the parameters. Here cou need to wrap the content in an array, because concat concatinates arrays.
var arr = [0],
elem = [1, 2, 3];
arr = arr.concat([elem]);
console.log(arr);

How do I change a JavaScript array in place?

How do I change a JS array in place (like a Ruby "dangerous" method, e.g. with trailing !)
Example:
If I have this:
var arr = [1, 2, 3]
How can I make this:
arr === [2, 4, 6]
(assuming I have an appropriate function for doubling numbers) in one step, without making any more variables?
Use Array.prototype.forEach() , third parameter is this : input array
var arr = [1, 2, 3];
arr.forEach(function(el, index, array) {
array[index] = el * 2
});
console.log(arr)
A smart Array.prototype.map() and an assignment will do.
The map() method creates a new array with the results of calling a provided function on every element in this array.
var arr = [1, 2, 3];
arr = arr.map(function (a) {
return 2 * a;
});
document.write('<pre>' + JSON.stringify(arr, 0, 4) + '</pre>');
map() returns a new array, but it can also modify the array in-place if the callback function works on the array's elements:
function double(el, i, array) {
array[i]= el * 2;
} //double
var arr= [1, 2, 3];
arr.map(double);
console.log(arr); // [2, 4, 6]

Remove elements from array using javascript filter

I have two arrays and want to remove duplicates using filter function.
Here is my code:
arr1 = [1, 2, 3, 1, 2, 3];
arr2 = [2, 3];
result = [1, 1];
var result = arr1.filter(function(value, index) {
for (var i = 0; i <= arr2.length; i++) {
if (value !== arr2[i]) {
return value === arr2[i];
}
}
}
Thanks in advance! Any help would be great!
You can try to convert arguments into array and then check if the value from the initial array is in arguments array:
function destroyer(arr) {
// Converting arguments into array
var args = Array.prototype.slice.call(arguments);
arr = arr.filter(function (val) {
return args.includes(val)===false;
});
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3); // returns[1,1]
First of all, if its not a problem adding a library. I am using uniq from underscore.js.
uniq_.uniq(array, [isSorted], [iteratee]) Alias: unique
Produces a duplicate-free version of the array, using === to test object
equality. In particular only the first occurence of each value is
kept. If you know in advance that the array is sorted, passing true
for isSorted will run a much faster algorithm. If you want to compute
unique items based on a transformation, pass an iteratee function.
_.uniq([1, 2, 1, 4, 1, 3]);
=> [1, 2, 4, 3]
Other solution is using pure JS:
var newArray = [1, 2, 2, 3, 3, 4, 5, 6];
var unique = newArray.filter(function(itm, i, a) {
return i == newArray.indexOf(itm);
});
alert(unique);
But first you will need to combine your arrays in a new array:
var newArray = arr1.concat(arr2);
JS Fiddle
I hope this helped! :)
Here's one way without the filter function:
var arr1 = [1, 2, 3, 1, 2, 3];
var newArr = [];
for(var i = 0;i < arr1.length;i++){
if (newArr.indexOf(arr1[i]) === -1) {
newArr.push(arr1[i]);
}
}
Just use Array.prototype.filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
with Array.prototype.indexOf()
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
var arr1 = [1, 2, 3, 1, 2, 3],
arr2 = [2, 3],
result = arr1.filter(function (a) {
return !~arr2.indexOf(a);
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
As in this JS Fiddle, using filter()
arr1 = [1, 2, 3, 1, 2, 3];
arr2 = [2, 3];
result = [1, 1];
var result = arr1.filter(myFunc);
function myFunc(value) {
for (var i = 0; i < arr2.length; ++i) {
// to remove every occurrence of the matched value
for (var j = arr1.length; j--;) {
if (arr1[j] === arr2[i]) {
// remove the element
arr1.splice(j, 1);
}
}
}
}
document.getElementById('result').innerHTML = arr1;
console.log(arr1);
// Output: [1,1]
<div id="result"></div>

How to select all other values in an array except the ith element?

I have a function using an array value represented as
markers[i]
How can I select all other values in an array except this one?
The purpose of this is to reset all other Google Maps images to their original state but highlight a new one by changing the image.
Use Array​.prototype​.splice to get an array of elements excluding this one.
This affects the array permanently, so if you don't want that, create a copy first.
var origArray = [0,1,2,3,4,5];
var cloneArray = origArray.slice();
var i = 3;
cloneArray.splice(i,1);
console.log(cloneArray.join("---"));
You can use ECMAScript 5 Array.prototype.filter:
var items = [1, 2, 3, 4, 5, 6];
var current = 2;
var itemsWithoutCurrent = items.filter(function(x) { return x !== current; });
There can be any comparison logics instead of x !== current. For example, you can compare object properties.
If you work with primitives, you can also create a custom function like except which will introduce this functionality:
Array.prototype.except = function(val) {
return this.filter(function(x) { return x !== val; });
};
// Usage example:
console.log([1, 2, 3, 4, 5, 6].except(2)); // 1, 3, 4, 5, 6
You can also use the second callback parameter in Filter:
const exceptIndex = 3;
const items = ['item1', 'item2', 'item3', 'item4', 'item5'];
const filteredItems = items.filter((value, index) => exceptIndex !== index);
You can use slice() Method
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1,3);
The slice() method returns the selected elements in an array, as a new array object.
This function will return a new array with all elements except the element at the specified index:
const everythingBut = (array, i) => { /*takes an array and an index as arguments*/
let notIArray = []; /*creates new empty array*/
let beforeI = array.slice(0, i); /*creates subarray of all elements before array[i]*/
let afterI = array.slice(i+1,); /*creates subarray of all elements after array[i]*/
notIArray = [...beforeI, ...afterI]; /*add elements before and after array[i] to empty array*/
return notIArray; /*returns new array with array[i] element excluded*/
};
For example:
let array = [1, 2, 4, 7, 9, 11, 2, 6]
everythingBut(array, 2); /*exclude array[2]*/
// -> [1, 2, 7, 9, 11, 2, 6]
Another way this can be done is by using filter and slice Array methods.
let array = [ 1, 2, 3, 4, 5, 6 ];
let leave = 2;
// method 1
console.log(array.filter((e,i) => i !== leave));
// logs [1, 2, 4, 5, 6];
//method 2
console.log([...array.slice(0, leave), ...array.slice(leave+1, array.length)]);
// logs [1, 2, 4, 5, 6];
You can combine Array.prototype.slice() and Array.prototype.concat() in using startingArray.slice(desiredStartIndex, exclusionIndex).concat(startingArray.slice(exclusionIndex+1)) to exclude the item whose index is exclusionIndex.
E.g., if you have a startingArray of [0, 1, 2] and want a desiredArray of [0, 2], then you can do as follows:
startingArray = [0, 1, 2];
desiredStartIndex = 0;
exclusionIndex = 1;
desiredEndIndex = 2;
desiredArray = startingArray.slice(desiredStartIndex,
exclusionIndex).concat(startingArray.slice(exclusionIndex+1));
With ECMAScript 5
const array = ['a', 'b', 'c'];
const removeAt = 1;
const newArray = [...array].splice(removeAt, 1);

Categories

Resources