How do I change a JavaScript array in place? - javascript

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]

Related

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);

Suming a nested array's indices together with JavaScript map

Working to get a better grasp of nested arrays. I have an array with two arrays nested inside as the indices. I am trying to figure out how to add these. I understand how you would add them if they were separate arrays, but I am wondering how/if possible you can map through a nested array to add the indices.
The current array that I am looking at is
strArr= [[5, 2, 3], [2, 2, 3] ];
If this was two separate arrays I could simply run a map with index as a second parameter such as ...
var arr = [1,2,3,4];
var arr2 = [1,1,1,2,9];
arr.map((a, i) => a + arr2[i]);
However, I am not able to achieve this with the index
strArr.map((a,idx) => a[0][idx] + a[1][idx]) // [Nan, Nan]
The best I can do to get any addition is
return strArr.map(a => a[0] + a[1]) // [7,4]
However, I am not sure why I am only getting [7,4]
You iterate over the outer array, which has a length of 2. Therefore you get a result of two elements.
You could use Array#reduce for the outer array and Array#forEach for the inner arrays and sum the values at a given index.
var strArr= [[5, 2, 3], [2, 2, 3] ];
console.log(strArr.reduce((r, a) => (a.forEach((b, i) => r[i] = (r[i] || 0) + b), r), []));
You can use the .reduce function to sum your indices
var arr = [1, 2, 3, 4];
var arr2 = [1, 1, 1, 2];
var result = arr
.map((item, i) => i + arr2[i])
.reduce((memo, value) => memo + value);
console.debug("res: ", result);
// res: 11
However you will have to handle cases when the array lengths are not equal to eachover or not numerical values
Map each element in the parent array (sub-arrays)
For each sub-array reduce and sum
strArr= [[5, 2, 3], [2, 2, 3] ];
var result = strArr.map((arr)=>arr.reduce((a,b)=>a+b));
console.log(result);
Why not just target/split the original array?
"If this was two separate arrays I could simply run a map with index as a second parameter"
Then make it two separate arrays...
strArr= [[5, 2, 3], [2, 2, 3] ]; /* becomes strArr[0] & strArr[1] */
console.log(strArr[0].map((a, i) => a + strArr[1][i]));

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>

Merging of two arrays, store unique elements, and sorting in jQuery

var Arr1 = [1,3,4,5,6];
var Arr2 = [4,5,6,8,9,10];
I am trying to do merge these two arrays and output coming is [1,3,4,5,6,4,5,6]
I have used $.merge(Arr1, Arr2); this piece to merge them. Using alert I can see the merged array like above.
Now my question is how can I get the following output:
[1,3,4,5,6,8,9,10]
i.e. the elements should be unique as well as sorted in the same manner I have mentioned.
Please help.
You can use Array.prototype.sort() to do a real numeric sort and use Array.prototype.filter() to only return the unique elements.
You can wrap it into a helper similar to this:
var concatArraysUniqueWithSort = function (thisArray, otherArray) {
var newArray = thisArray.concat(otherArray).sort(function (a, b) {
return a > b ? 1 : a < b ? -1 : 0;
});
return newArray.filter(function (item, index) {
return newArray.indexOf(item) === index;
});
};
Note that the custom sort function works with numeric elements only, so if you want to use it for strings or mix strings with numbers you have to update it off course to take those scenarios into account, though the rest should not change much.
Use it like this:
var arr1 = [1, 3, 4, 5, 6];
var arr2 = [4, 5, 6, 8, 9, 10];
var arrAll = concatArraysUniqueWithSort(arr1, arr2);
arrAll will now be [1, 3, 4, 5, 6, 8, 9, 10]
DEMO - concatenate 2 arrays, sort and remove duplicates
There is many ways of doing this I'm sure. This was just the most concise I could think off.
merge two or more arrays + remove duplicities + sort()
jQuery.unique([].concat.apply([],[[1,2,3,4],[1,2,3,4,5,6],[3,4,5,6,7,8]])).sort();
One line solution using just javascript.
var Arr1 = [1,3,4,5,6];
var Arr2 = [4,5,6,8,9,10];
const sortedUnion = [... new Set([...Arr1,... Arr2].sort((a,b)=> a-b))]
console.log(sortedUnion)
This looks like a job for Array.prototype.indexOf
var arr3 = arr1.slice(), // clone arr1 so no side-effects
i; // var i so it 's not global
for (i = 0; i < arr2.length; ++i) // loop over arr2
if (arr1.indexOf(arr2[i]) === -1) // see if item from arr2 is in arr1 or not
arr3.push(arr2[i]); // it's not, add it to arr3
arr3.sort(function (a, b) {return a - b;});
arr3; // [1, 3, 4, 5, 6, 8, 9, 10]
a = [1, 2, 3]
b = [2, 3, 4]
$.unique($.merge(a, b)).sort(function(a,b){return a-b}); -> [1, 2, 3, 4]
Update:
This is a bad idea, since the 'unique' function is not meant for use on numbers or strings.
However, if you must then the sort function needs to be told to use a new comparator since by default it sorts lexicographically.
Using underscore.js:
_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]).sort(function(a,b){return a-b});
=> [1, 2, 3, 10, 101]
This example is taken directly from underscore.js, a popular JS library which complements jQuery
I did that as follows, where t1 and t2 are my two tables.
The first command put the values of the table t2 to the t1. The second command removes the duplicate values from the table.
$.merge(t1, t2);
$.unique(t1);
function sortUnique(matrix) {
if(matrix.length < 1 || matrix[0].length < 1) return [];
const result = [];
let temp, ele;
while(matrix.length > 0) {
temp = 0;
for(let j=0; j<matrix.length; j++) {
if(matrix[j][0] < matrix[temp][0]) temp = j;
}
if(result.length === 0 || matrix[temp][0] > result[result.length-1]) {
result.push(matrix[temp].splice(0,1)[0]);
} else {
matrix[temp].splice(0,1);
}
if(matrix[temp].length===0) matrix.splice(temp, 1);
}
return result;
}
console.log(sortUnique([[1,4,8], [2,4,9], [1,2,7]]))
Using JavaScript ES6 makes it easier and cleaner. Try this:
return [...Arr1, ...Arr2].filter((v,i,s) => s.indexOf(v) === i).sort((a,b)=> a - b);
and there you have it. You could build it in a function like:
function mergeUniqueSort(Arr1, Arr2){
return [...Arr1, ...Arr2].filter((v,i,s) => s.indexOf(v) === i).sort((a,b)=> a - b);
}
and that settles it. You can also break it down using ES6. Use a Spread Operator to combine arrays:
let combinedArrays = [...Arr1, ...Arr2]
then get the unique elements using the filter function:
let uniqueValues = combinedArrays.filter((value, index, self ) => self.indexOf(value) === index)
Lastly you now sort the uniqueValue object:
let sortAscending = uniqueValues.sort((a-b) => a - b) // 1, 2, 3, ....10
let sortDescending = uniqueValues.sort((b-a) => b - a) // 10, 9, 8, ....1
So you could use any part, just in case.

Add to Array jQuery

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);
}

Categories

Resources