Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access every other item in an array - JavaScript

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!

like image 771
Rafill Avatar asked Jun 08 '15 15:06

Rafill


People also ask

How do I get every other element in an array?

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.

How would you access the 2nd to last element in an 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.

What does every () do?

every() The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

Can I filter an array of objects JavaScript?

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.


3 Answers

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;
  });
};
like image 198
Robert Wallen Avatar answered Oct 22 '22 02:10

Robert Wallen


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]
like image 32
dannymac Avatar answered Oct 22 '22 01:10

dannymac


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

like image 5
T.J. Crowder Avatar answered Oct 22 '22 01:10

T.J. Crowder