How to Increase by 1 All Keys in an Array

How to increase by 1 all keys in an array?

You can use

$start_zero = array_values($array); /* Re-Indexing Array To Start From Zero */

And if you want to start it from index 1 use

$start_one = array_combine(range(1, count($array)), array_values($array));

PHP Increment array keys +1

$data = [
0 => [7 => 'foo', 13 => 'foo'],
1 => [2 => 'foo', 25 => 'foo'],
4 => [24 => 'foo'],
];

// top level
$data = array_combine(
array_map(function ($key) { return ++$key; }, array_keys($data)),
$data
);
// then the elements (use array_walk_recursive() if you have more levels)
array_walk(
$data,
function(&$data) {
$data = array_combine(
array_map(function ($key) { return ++$key; }, array_keys($data)),
$data
);
}
);
var_dump($data);

Demo

Increment a key's value (+1) within a series of objects contained in an array that's held in useState

map should return the object instead of array.

const items = [  { name: "foo", wait: 1 },  { name: "bar", wait: 5 },];
const updated = items.map((item) => ({ ...item, wait: item.wait + 1 }));
// setItems(items.map(item => ({...item, wait: item.wait + 1})));
console.log(updated);

How to properly increment some array key, even if key needs to be created?

After some reading, writing and testing I got something:

function inc(&$var){
if (isset($var)) $var++;else $var=1;
}

and thought I struck gold, but let's see the tests first...

Test code:

$a=array();

// Pre-Fill array code goes here
for($i=1;$i<100000;$i++) {
$r=rand(1,30000);
//increment code goes here
}

// Remove extra keys from array with:
//foreach ($a as $k=>$v) if ($v==0) unset($a[$k]);

Execution times: (for informative purposes only)

inc($a[$r])                             1.15-1.24
@$a[$r]++ 1.03-1.09
$a[$r]=array_key_exists($r,$a)?$a[$r]++:1; 0.99-1.04

$a[$r]=!empty($a[$r])?$a[$r]++:1; 0.61-0.74
if (!empty($a[$r])) $a[$r]++;else $a[$r]=1; 0.59-0.67
$a[$r]=isset($a[$r])?$a[$r]++:1; 0.57-0.65
if (isset($a[$r])) $a[$r]++;else $a[$r]=1; 0.56-0.64

//with pre-fill
$a=array_fill(0,30000,0); +0.07(avg)
for($i=1;$i<=30000;$a[$i++]=0); -0.04(avg)

//with pre-fill and unset
$a=array_fill(0,45000,0); +0.16(avg)
for($i=1;$i<=45000;$a[$i++]=0); +0.02(avg)

Conclusions:

  • @ is of course the fastest to type and I don't see any problem in using it in this case but feel free to check this question also: Suppress error with @ operator in PHP
  • completely suppressing errors (before the loop and enabling errors after the loop) via ini_set() is worse than all on performance
  • inc() looks nice and clean, easy to type and does checking instead of suppressing, but calling it looks to be even slower than @
  • isset() is slightly faster than empty(), but both perform fairly the same
  • interestingly using shorthand if statements is slightly slower!
  • best results achieved when pre-filling the array. Even if length is unknown a good prediction would be still slightly faster on a huge dataset
  • strangely, array_fill() takes slightly longer than for ?!?!

RFC

I don't consider this answer 100% complete, although, for now it looks like isset() is the fastest and @ the laziest.

Any comments and ideas are appreciated!

How do I build up in a map with one Key with many Values in Java 7

Hope the code is self explanatory.

Java 7:

public Map<String, List<String>> group(String[] input) {
Map<String, List<String>> result = new HashMap<>();

for (String str : input) {
String key = "Letter " + str.charAt(0);
if (result.containsKey(key)) {
result.get(key).add(str);//if Key already exists, just add this word to existing list.
} else {
List<String> list = new ArrayList<>();
list.add(str);
result.put(key, list); //Otherwise, create a new list and add the new word into the list
}
}
return result;
}

Java 8:

public static Map<String, List<String>> group(String[] input) {
return Arrays.stream(input)
.collect(Collectors.groupingBy(k -> "Letter " + k.charAt(0)));
//Provide the key for how you want to group. In your case it is first character of string.
}

How to create an array containing 1...N

If I get what you are after, you want an array of numbers 1..n that you can later loop through.

If this is all you need, can you do this instead?

var foo = new Array(45); // create an empty array with length 45

then when you want to use it... (un-optimized, just for example)

for(var i = 0; i < foo.length; i++){
document.write('Item: ' + (i + 1) + ' of ' + foo.length + '<br/>');
}

e.g. if you don't need to store anything in the array, you just need a container of the right length that you can iterate over... this might be easier.

See it in action here: http://jsfiddle.net/3kcvm/

Increase an Object key in a JS array

Using a map from tag names to properties will be much easier and more efficient:

// pick a better name
const map = new Map();

for (const content of contents) {
for (const tagName of content.tags) {
let tagObject = map.get(tagName);

if (tagObject === undefined) {
map.set(tagName, tagObject = {
contentID: new Set(),
occurrences: 0,
});
}

tagObject.occurrences++;
tagObject.contentID.add(content.contentID);
}
}

Then you can convert it to the array format:

const tagManagerArr = Array.from(map,
([tagName, {contentID, occurrences}]) => ({
tagName,
contentID: Array.from(contentID),
occurrences,
}));


Related Topics



Leave a reply



Submit