agwooga33
agwooga33

Reputation: 11

How do i move through the values of keys in javascript?

How would i cycle move the key values in a js array,

for example:
    {Name:"A", Task:"Task1"},
    {Name:"B", Task:"Task2"},
    {Name:"C", Task:"Task3"},

to
    {Name:"A", Task:"Task3"},
    {Name:"B", Task:"Task1"},
    {Name:"C", Task:"Task2"},

to clarify further it should be a function that every time is run "shifts the task column" by one.

I have tried using methods such as:

ary.push(ary.shift()); 

however i don't know any way that i can specifically apply this to a specific key while not moving the others.

Upvotes: 1

Views: 99

Answers (3)

charlietfl
charlietfl

Reputation: 171690

Approach using a Generator and your pop and shift concept

const data=[{Name:"A",Task:"Task1"},{Name:"B",Task:"Task2"},{Name:"C",Task:"Task3"}];

function* taskGen(data){
   // create standalone array of the names that can be shifted
   const tasks = data.map(({Task}) => Task);
   while(true){
      // move first to last position
      tasks.push(tasks.shift());
      // return new mapped array
      yield data.map((o, i) => ({...o, Task: tasks[i] }))
   }
}

const shifter = taskGen(data);

for (let i =0; i< 6; i++){
   const next = shifter.next().value
   console.log(JSON.stringify(next))
}
.as-console-wrapper {max-height: 100%!important;top:0;}

Upvotes: 0

Miki
Miki

Reputation: 1818

You are very close. You can decompose the array into two individual ones and shift one of them. See below function:

const arr = [
  { Name: "A", Task: "Task1" },
  { Name: "B", Task: "Task2" },
  { Name: "C", Task: "Task3" }
];

function cycle(arr) {
  const names = arr.map(el => el.Name);
  const tasks = arr.map(el => el.Task);
  const el = tasks.pop();
  tasks.unshift(el);
  return names.map((letter, i) => {
    return {
      Name: letter,
      Task: tasks[i]
    };
  });
}
console.log(cycle(arr));

Also, codepen for conveninence.

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 192607

Map the array, and take the task from the previous item in the cycle using the modulo operation.

Unlike the % operator the result of using modulo with negative numbers would be a positive remainder. It's needed because in the first item (i is 0) i - 1 would be -1.

const modulo = (a, n) => ((a % n ) + n) % n

const fn = arr =>
  arr.map((o, i) => ({
    ...o,
    Task: arr[modulo((i - 1), arr.length)].Task
  }))

const arr = [{"Name":"A","Task":"Task1"},{"Name":"B","Task":"Task2"},{"Name":"C","Task":"Task3"}]

const result = fn(arr)

console.log(result)

Upvotes: 1

Related Questions