End array map at an index? - javascript

Is it possible to only map an array up to a certain index?
For example, say I have the following:
var nums = [1, 2, 3, 4, 5];
I want to sum up the numbers in the array, but only up to the 3rd index. Is it possible to pass in an argument to Array.map() to only go up to a given index? Or is this only possible using a for loop?

Just use slice.
The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.
nums.slice(0,3).map(...);

By definition, map() is called on every element in the array. See the docs for details here. So, yes, you would need to use a different solution such as a for loop.

you can use slice() to get array till a specific index
nums.slice(0,3).map();

you can use slice() function which returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.
nums.slice(0,3).map(//your code);
for more information
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

Related

Return an array with only first 3 character/numbers from each item in an arrays

How can I return only the first 3 characters/digits from each item in an array?
For example: The string 123456 should return 123, 987654 should return 987, and so on.
Given an array of:
['7177576', '4672769', '2445142', '9293878', '5764392']
Expected return:
['717', '467','244', '929', '576']
I have tried .slice() but that returns the first three like this:
['7177576', '4672769', '2445142'].
slice works for strings, too.
const
data = ['7177576', '4672769', '2445142', '9293878', '5764392'],
result = data.map(string => string.slice(0, 3));
console.log(result);
JavaScript has many methods for manipulating arrays. The map method creates a new array populated with the results of calling a provided function on every element in the calling array. As Nina Scholz mentions above you can use slice on strings as well.
The issue you are having is that you are calling slice on the array and not on the items of the array.
You need to do something like Nina Suggest which is to map over the main array and call your slice function for each item.

How to show only 20 object from Array in typescript?

I am using angular 7. I have initialized an array given as:
cacheDatas=[];
Here cacheData has 1000 of object which are initialized to cacheDatas but I only need 20 object.
getDataOfCache(cacheData:any){
this.cacheDatas=cacheData;
this.cacheDatas.slice(0,20);
console.log(this.cacheDatas);
}
I tried to implement the slice method but it is not working. The value cacheData:any is:
Need to assign the value for the variable: cacheDatas after slice.
this.cacheDatas = this.cacheDatas.slice(0,20);
Example here: https://stackblitz.com/edit/angular-3d4ypz
you can use splice method but this method will method changes the contents of an array by removing
this.cacheDatas.splice(20);
another option is the slice method same as you question but this methos method returns a shallow copy of a portion of an array into a new array object
const result = this.cacheDatas.slice(0,20);
console.log(result)
slice() method does not modify the array but returns a new array with the required elements. So you can use the below to solve your problem -
getDataOfCache(cacheData:any){
this.cacheDatas=cacheData;
this.cacheDatas=this.cacheDatas.slice(0,20);
console.log(this.cacheDatas);
}
Or you can use the splice() method (note the change in spelling). It will modify the original array as per the given input. If only one index is given as input, then it will remove all the elements from that index to the end of the array. So you can use this code as well -
getDataOfCache(cacheData:any){
this.cacheDatas=cacheData;
this.cacheDatas.splice(20);
console.log(this.cacheDatas);
}

Why is filter method not deleting all elements of the array?

this.arol.filter(x=>x.length!==0
?(this.arol.splice(this.arol.indexOf(x),1))
:!true)
I was trying to change it many different ways, but it still does not delete all elements of the array, it always leaves 1 or 2 behind deleting most of them.... I think the problem is with the condition... We are checking if the length of array elements is not 0 (which are all strings)...
Don't try to splice while filtering - instead, return from the filter callback a truthy or falsey value, depending on whether you want to include the item being iterated over in the new array, and use the resulting array that gets returned from .filter:
this.arol = this.arol.filter(x => x.length !== 0);
^^^^^^^^^^^^
If you want to maintain same outer array reference and mutate original you can splice in a loop if you work from end to start so as not to affect indexing you haven't arrived at yet as you change the array length:
const arr = [[1],[],[2]]
arr.reduceRight((_,c,i) => c.length || !!arr.splice(i,1))
console.log(arr)
The problem is you are trying to splice at the same time you are using filter. Filter does not remove elements from your array, it creates a new array with the filtered data, as described here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
You can assign the result to the same array as suggested by CertainPerformance.
If Splice is removed from that code then it will not delete elements. this.arol.splice(this.arol.indexOf(x),1) here it will iterate through every element inside that array and x will be current iteration which will splice from the array as you have written splice method. Remove splice it will work fine.

Javascript slice isn't giving me correct array length values

Why does it say length 1 instead of 4?
The following is what I'm trying to push and slice. I try and append items.image_urls and slice them into 5 each.
items.image_urls is my dictionary array.
var final_push = []
final_push.push(items.image_urls.splice(0,5))
console.log(final_push.length)## gives me 1...?
var index = 0
final_push.forEach(function(results){
index++ ##this gives me one. I would need 1,2,3,4,5,1,2,3,4,5. Somehting along that.
}
items.image_urls looks like this:
It's an iteration of arrays with image urls.
In your example items.image_urls.splice(0,5) returns an array of items removed from items.image_urls. When you call final_push.push(items.image_urls.splice(0,5));, this whole array is pushed as one item to the final_push array, so it now looks like [["url1", "url2", "url3", "url4", "url5"]] (2-dimensional array). You can access this whole array by calling final_push[some_index].
But what you want instead is to add every element of items.image_urls.splice(0,5) to the final_push. You can use a spread operator to achieve this:
final_push.push(...items.image_urls.splice(0,5));
Spread syntax allows an iterable such as an array expression or string
to be expanded in places where zero or more arguments (for function
calls) or elements (for array literals) are expected
This is exactly our case, because push() expects one or more arguments:
arr.push(element1[, ...[, elementN]])
And here is an example:
let items = {
image_urls: ["url1", "url2", "url3", "url4", "url5", "url6", "url7", "url8", "url9", "url10"]
};
let final_push = [];
final_push.push(...items.image_urls.splice(0,5));
console.log(final_push.length);
console.log(JSON.stringify(final_push));
console.log(JSON.stringify(items.image_urls));
Note: do not confuse Array.prototype.slice() with Array.prototype.splice() - the first one returns a shallow copy of a portion of an array into a new array object while the second changes the contents of an array by removing existing elements and/or adding new elements and returns an array containing the deleted elements.
That seems to be a nested array. So if you would access index 0, and then work on that array like below it will probably work:
console.log(final_push[0].length); //should print 4
The author is mixing up splice and slice. Probably a typo :)
You start at the beginning (0) and then delete 5 items.

Array Self-Referencing Map - Very Bizarre Result

While experimenting with some different methods for generating JavaScript arrays, I stumbled on a weird result. Using map to push an array of self-references (DEMO):
a=[1,1,1,1,1,1,1,1,1,1];
a=a.map(a.push,a);
I get the following result (in Chrome):
[13,16,19,22,25,28,31,34,37,40]
Can anyone explain why?
For each element in a, push is being called with that element, the index of that element, and the array being traversed. For each element in the array, then, we add these three additional elements. This accounts for the length increasing by three for each element in the original array. The result of push is the length of the array after the elements are added, thus the resulting array (from map) is an array holding the lengths of the a array after each push callback is completed.
See the documentation for map and push.
It has something to do with the return value of push being the new length. Not sure why it incrementing by 3.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/push
Returns
The new length property of the object upon which the method was called.

Categories

Resources