Is it possible for me to access every other item in an array? So basically, all items in positions 0, 2, 4, 6 etc.
Here's my code if it helps:
function pushToHash(key, value) {
for (var t = 0; t < value.length; t++) {
MQHash[key[t]] = value.slice(0, lineLength[t]);
}
}
So, I need to get every other value of lineLength
. I only want this for lineLength
, not key
. I was thinking of doing a modulus, but wasn't sure how I'd implement it. Any ideas?
Thanks in advance!
To get every Nth element of an array: Declare an empty array variable. Use a for loop to iterate the array every N elements. On each iteration, push the element to the new array.
To get the second to last element in an array, call the at() method on the array, passing it -2 as a parameter, e.g. arr.at(-2) . The at method returns the array element at the specified index. When passed a negative index, the at() method counts back from the last item in the array.
every() The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.
Here is a function that will truncate an array every X elements (factor).
const truncateArray = (array: any[], factor: number): any[] => {
let lastNumber = 0;
return array.filter((element, index) => {
const shouldIncludeThisElement = index === lastNumber + factor ? true : false;
lastNumber = shouldIncludeThisElement ? index : lastNumber;
return shouldIncludeThisElement;
});
};
You can use the index (second parameter) in the array filter method like this:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// filter out all elements that are located at an even index in the array.
let x = arr.filter((element, index) => {
return index % 2 === 0;
})
console.log(x)
// [1, 3, 5, 7, 9]
If you just want this with lineLength
and not with key
, then add a second variable and use +=
when incrementing:
function pushToHash(key, value) {
for (var t = 0, x = 0; t < value.length; t++, x += 2) {
MQHash[key[t]] = value.slice(0, lineLength[x]);
}
}
(The power of the comma operator...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With