can y'all explain other methods to loop in the array ??
function blabla(number){
for ( let i = 0 ; i < number.length ; i++)
..........
}
console.log([1,2,3,4,5,6])// true
console.log([2,4,6,8]) // true
console.log([1,2,6,8,9,11, 25]) false
can we use forEach to loop? how about map and filter?
There's a ton of different ways to iterate through an array.
Let's use this array as an example: const array = ['foo', 'bar']
for..of
This will iterate through the values in the array.
const array = ['foo', 'bar']
for (element of array) {
console.log(element)
}
for..in
This will iterate through the properties in the array. In this case, that would be the array indexes. I wouldn't recommend this to iterate arrays, to be honest.
const array = ['foo', 'bar']
for (element in array) {
console.log(element)
}
Array.forEach()
This will run a callback for each one of the elements in an array. This allows you to pass a function to it, which will take each element as the parameter.
const array = ['foo', 'bar']
const doSomething = e => console.log(e)
array.forEach(element => console.log(element))
//or
array.forEach(doSomething)
Array.map()
This will run a callback for each one of the elements in an array, just like in the forEach method, but in that function you can return a value modifying the original value of the element, and the return value of the map function will be the array with the modified values.
This will add 'test' to the end of each of the elements, and return the resulting array.
const array = ['foo', 'bar']
const mappedArray = array.map(element => element.concat('test'))
console.log(mappedArray)
Array.filter()
This will run a function for each one of the elements in an array, and depending whether you return a truthy or falsy, it will include or exclude that element from the returning array
This will filter out all elements that contain the letter "f".
const array = ['foo', 'bar']
const filteredArray = array.filter(element => !element.includes('f'))
console.log(filteredArray)
Those are just some of them. I'd also recommend looking into Array.reduce(), Array.every() and Array.some().
this will start counting from 0
function blabla(number){
$.each(new Array(number),
function(n){alert(n);}
);
}
blabla(3);
Related
Given array:
const array = [{1: true},{2: false},{3: true},{}.....];
Filter the given array by only including objects with values of true.
Looking for the shortest solution.
const onlyTrue = array.filter((el, ind) => el[ind + 1] === true);
This will work only if indexes in array objects are ordered and starting from 1, as it is in your example.
Assumptions (based on what's in your example):
Each object in the array only has at least 1 property in it
The first property on each object is the one we care about
The property in each object is different every time
const array = [{1: true},{2: false},{3: true}];
const results = array.filter(item => Object.values(item)[0]);
If you want to avoid any false positives from truth-y values (see https://developer.mozilla.org/en-US/docs/Glossary/Truthy), then change the filter call to this instead:
const results = array.filter(item => Object.values(item)[0] === true);
const array = [{1: true},{2: false},{3: true}];
const array2 = [];
array.forEach(filterTrue);
function filterTrue(item){
for(x in item){
if(item[x]===true){
array2.push(item);
}
}
}
console.log(array2);
Hope this helps you.
i have an array like [x/0/2 , x/0/3 , y/3/1 , x/1/1 , x/0/3 , x/1/2],
i need to convert the elements range like [x/0/2-3 , y/3/1 , x/1/1-2]
Please give some suggestion for this.
Use reduce to iterate over the array and create an object grouped by the element root, then use Object.entries to pull out the correct information from the object.
const arr = ['x/0/2', 'x/0/3', 'y/3/1', 'x/1/1', 'x/0/3', 'x/1/2'];
const out = arr.reduce((acc, c) => {
// `split` out the separate parts of the element
const [ root1, root2, index ] = c.split('/');
// We'll use the first two parts as the object key
const key = `${root1}/${root2}`;
// If the key doesn't already exist create an empty
// array as its values
acc[key] = acc[key] || [];
// To prevent duplicates only add an index if it
// isn't already in the array
if (!acc[key].includes(index)) acc[key].push(index);
// Return the accumulator for the next iteration
return acc;
}, {});
// Then iterate over the object entries with `map`
const result = Object.entries(out).map(([ key, values ]) => {
// Return the joined up value
return `${key}/${values.join('-')}`;
});
console.log(result);
If I understand your question, you could create an array within the array to hold the range of values. Checking if the position in the array is an actual array let’s you know there are values that span a range within.
Example:
var values = [x/01, [x/20, x/21, x/22], x/03]
You could also create an object that could accomplish something similar depending on your needs.
I have two array of objects: - better solution
array1= [{id:1,name:"samsung"},{id:2,name:"nokia"},{id:3,name:"Lg"}];
array2 = [{id:5,name:"samsung"},{id:2,name:"panasonics"},{id:7,name:"Lg"}];
Expected output be:
if first array and second array id matches means take the second array name
in above example id 2 matches and we need id:2,name: panasonics.
o/p:
[{id:1,name:"samsung"},{id:2,name:"panasonics"},{id:3,name:"Lg"},{id:5,name:"samsung"},{id:7,name:"Apple"}]
Combine the arrays using Array.concat(), reduce them into a Map by id, and then convert the Map's values to an array with Array.from():
const unionBy = (field, ...arrays) => Array.from(
[].concat(...arrays)
.reduce((r, o) => r.set(o.id, o), new Map)
.values()
);
const array1 = [{id:1,name:"samsung"},{id:2,name:"nokia"},{id:3,name:"Lg"}];
const array2 = [{id:5,name:"samsung"},{id:2,name:"panasonics"},{id:7,name:"Lg"}];
const result = unionBy('id', array1, array2);
console.log(result);
You can use a simple .forEach() loop like below (you can also use a for loop if you want, but .forEach() is easier).
This code loops through array1, and loops through array2 in that loop. It then checks if the ids are the same. If there are, the name is appended to result.
const array1= [{id:1,name:"samsung"},{id:2,name:"nokia"},{id:3,name:"Lg"}];
const array2 = [{id:5,name:"samsung"},{id:2,name:"panasonics"},{id:7,name:"Lg"}];
let result = [];
array1.forEach(e1 => {
array2.forEach(e2 => {
if (e1.id == e2.id) {
result.push(e2.name);
}
});
});
console.log(result);
Use map() and concat() like the following code
array1= [{id:1,name:"samsung"},{id:2,name:"nokia"},{id:3,name:"Lg"}];
array2 = [{id:5,name:"samsung"}, {id:2,name:"panasonics"},{id:7,name:"Lg"}];
var array3=array1.map(function(i,v){
if(array2[v].id==i.id){
return array2[v]
}
else return i
})
array4=array3.concat(array2);
console.log(array4);
I am little confused on how to compare two array objects' particular value get that neglected values as an array.
var Arr1 = [
{
jobId:"j1"
},
{
jobId:"j2"
},
{
jobId:"j3"
},
{
jobId:"j4"
},
]
var Arr2 = [
{
jobId:"j1"
},
{
jobId:"j2"
},
]
I want my result like this...
//neglected values
[
{
jobId:"j3"
},
{
jobId:"j4"
},
]
So let's think about how to go about comparing things in two arrays.
It probably makes sense to assume in order to fully compare both arrays, we need to iterate them, making sure we compare every item in each array so that we can be sure
So if I was begining i would think of nesting for - loops. Why? Because it will iterate over the first array, on each index it hits the first array, it will then iterate over every element in the second array.
then you can create some basic if conditional logic like if Arr1[i] === Arr2[j], push one of the objects into an array.
Filter (Array#filter) down the elements of the first array to those for which there are not (!) some (Array#some) matching job IDs in the second array.
Arr1.filter(arr1Elt => !Arr2.some(arr2Elt => arr2Elt.jobId === arr1Elt.jobId))
Using line-by-line comment style:
Arr1 // From Arr1,
.filter( // keep
arr1Elt => // elements for which
! // it is not the case that
Arr2 // Arr2 has
.some( // some
arr2Elt => // elements for which
arr2Elt.jobId // the job ID
=== // is equal to
arr1Elt.jobId // the job ID from the first array.
)
)
You can use lodash's _.differenceBy() to find the items from Arr1 missing from Arr2.
var Arr1 = [{"jobId":"j1"},{"jobId":"j2"},{"jobId":"j3"},{"jobId":"j4"}];
var Arr2 = [{"jobId":"j1"},{"jobId":"j2"}];
// find items that are in Arr1, but not in Arr2, compare items by their jobId
var result = _.differenceBy(Arr1, Arr2 , 'jobId');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.3/lodash.min.js"></script>
You can use Array.prototype.filter on Arr1 and check if any of its entries are in Arr2 using Array.prototype.some - see demo below:
var Arr1=[{jobId:"j1"},{jobId:"j2"},{jobId:"j3"},{jobId:"j4"}];
var Arr2=[{jobId:"j1"},{jobId:"j2"}];
var result = Arr1.filter(function(e){
return !Arr2.some(function(k){
return k.jobId === e.jobId;
});
});
console.log(result);
I am just wondering why it is not possible to make forEach on array of undefined.
Code:
var arr = new Array(5); // [undefined x 5]
//ES5 forEach
arr.forEach(function(elem, index, array) {
console.log(index);
});
//underscore each
_.each(arr, function(elem, index, array) {
console.log(index);
});
Both examples do not execute function.
Now to make foreach, I have to make:
var arr = [0,0,0,0,0];
Then make forEach on it.
I am trying to make an array with specified size and loop through it, avoiding for loop. I think that it is clearer using forEach than for loop.
With array with length 5 it is not a problem, but it would be ugly with bigger arrays.
Why there is a problem looping through array of undefined values ?
Array(5) is essentialy equivalent to
var arr = [];
arr.length = 5;
In javascript changing array's length doesn't set any values for it's numeric properties nor does it define those properties in the array object. So numeric properties are undefined instead of having undefined value. You can check it by using:
Object.keys(arr)
When iterating javascript iterates through numeric properties of the array, so if these don't exist, there is nothing to iterate over.
You can check it by doing:
var arr = Array(5)
//prints nothing
arr.forEach(function(elem, index, array) {
console.log(index);
});
arr[3] = 'hey'
//prints only 'hey' even though arr.length === 5
arr.forEach(function(elem, index, array) {
console.log(index);
});
The following code:
var arr = [undefined, undefined];
creates and array of length ===2 and sets the both numeric properties 0 and 1 to undefined.
Looking at a simplified implementation of .forEach() may help.
Array.prototype.my_for_each = function(callback, thisArg) {
for (var i = 0; i < this.length; i++) {
if (i in this) {
callback.call(thisArg, this[i], i, this);
}
}
};
So you can see that what happens is that the method does iterate the entire Array (according to the spec), but it only invokes the callback if the member actually exists. It checks by looking for the property (the index) using the in operator, which tests to see if the object either has or inherits the property.
If in shows that the index exists, the callback is invoked.
So given this Array:
var arr = ["foo", "bar", "baz"];
This will output all 3 items:
arr.my_for_each(function(item) {
console.log(item);
});
// "foo" "bar" "baz"
But if we use delete to remove a member, it leaves a hole in the Array, which will now get passed over.
delete arr[1];
arr.my_for_each(function(item) {
console.log(item);
});
// "foo" "baz"
When you created an Array using Array(5), it created one without any members, but with the .length set to 5. So this is an example of a sparse Array (very sparse in this instance). Because none of the indices will be found by in, the callback is never invoked.
You can use Array.from to create an array and pass lambda function that will be invoked on each item in the array.
detailed documentation
const arr = Array.from(
{ length: 5 },
() => 0
)
console.log(arr)
Other answers have explained the problem, but not provided solutions.
ES6 Spread syntax fills in sparse values with undefined. So does Array.apply(null, sparseArray), which has the benefit of working in older browsers, but takes a bit more work to understand.
const sparseArray = new Array(5);
const unsparseArray1 = Array.apply(null, sparseArray);
const unsparseArray2 = [...sparseArray];
function arrayApply() {
// ES5 forEach works with either approach
unsparseArray1.forEach(function(elem, index, array) {
console.log(index);
});
}
function es6Spread() {
// Lodash each works with either approach
_.each(unsparseArray2, function(elem, index, array) {
console.log(index);
});
}
<html><head>
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.21/lodash.min.js"></script>
<title>Making sparse arrays unsparse</title>
</head><body>
<p><button onclick="arrayApply();">Array.apply(null, sparseArray)</button></p>
<p><button onclick="es6Spread();">[...sparseArray]</button></p>
</body>
</html>
In my case, I was looking for an elegant solution to creating an array of digits starting with 0 to X.
In an elegant manner with arrow functions, it comes up with a 1 line of code
const arrayLength = 10;
const arrayOfDigits = Array.apply(null, Array(arrayLength)).map((_, index) => index);
Appeared to me quite a sophisticated one, much more than a separate block of code with a for cycle.