3

I have data something like this

const data = [
  {
    name: 'name1',
    id: 'id1'
  },
  {
    name: 'name2',
    id: 'id2'
  },
  {
    name: 'name3',
    id: 'id3'
  },
  {
    name: 'name4',
    id: 'id4'
  },
  {
    name: 'name5',
    id: 'id5'
  },
  {
    name: 'name6',
    id: 'id6'
  },
  {
    name: 'name7',
    id: 'id7'
  },
  {
    name: 'name8',
    id: 'id8'
  },

]

i need to push all objects up to id3 (not include id3) into one array and from id3 to id6 (not inclue id6) into one array, rest of things into another array.

between id1 and id3 any number of objects will add but we need to push until id3, same way we can add number of objects into id3 to id6.

finally i try to achieve like this

firstArr = [
   {
    name: 'name1',
    id: 'id1'
  },
  {
    name: 'name2',
    id: 'id2'
  }
]

secondArr = [
  {
    name: 'name3',
    id: 'id3'
  },
  {
    name: 'name4',
    id: 'id4'
  },
  {
    name: 'name5',
    id: 'id5'
  }
]

thirdArr = [
  {
    name: 'name6',
    id: 'id6'
  },
  {
    name: 'name7',
    id: 'id7'
  },
  {
    name: 'name8',
    id: 'id8'
  }
]

here the order like id3 and id6 won't change so that we can take this as reference.

2
  • 2
    So what's the issue? Parse your JSON, iterate over the array and add items to other arrays as required. Commented Apr 11, 2019 at 14:05
  • So id1,id2,anyId,anotherId,id3,id4,something,id6,id7 should be split this way: id1,id2 | anyId,anotherId,id3,id4,something | id6,id7 ? Commented Apr 11, 2019 at 14:20

7 Answers 7

2

You can use Array.slice() and Array.findIndex():

const id3Index = data.findIndex(obj => obj.id === 'id3');
const id6Index = data.findIndex(obj => obj.id === 'id6');
const arr1 = data.slice(0, id3Index);
const arr2 = data.slice(id3Index, id6Index);
const arr3 = data.slice(id6Index);

const data = [
  {
    name: 'name1',
    id: 'id1'
  },
  {
    name: 'name2',
    id: 'id2'
  },
  {
    name: 'name3',
    id: 'id3'
  },
  {
    name: 'name4',
    id: 'id4'
  },
  {
    name: 'name5',
    id: 'id5'
  },
  {
    name: 'name6',
    id: 'id6'
  },
  {
    name: 'name7',
    id: 'id7'
  },
  {
    name: 'name8',
    id: 'id8'
  },

]

const id3Index = data.findIndex(obj => obj.id === 'id3');
const id6Index = data.findIndex(obj => obj.id === 'id6');
console.log(data.slice(0, id3Index));
console.log(data.slice(id3Index, id6Index));
console.log(data.slice(id6Index));

Sign up to request clarification or add additional context in comments.

Comments

2

You can use findIndex() and then use slice()

I think its not good idea to make variables like firstArr,... instead you can create array of arrays

const data = [ { name: 'name1', id: 'id1' }, { name: 'name2', id: 'id2' }, { name: 'name3', id: 'id3' }, { name: 'name4', id: 'id4' }, { name: 'name5', id: 'id5' }, { name: 'name6', id: 'id6' }, { name: 'name7', id: 'id7' }, { name: 'name8', id: 'id8' }, ]


function split(data,...strs){
  let res = [];
  let last = 0;
  strs.forEach((x,i) => {
    let index = data.findIndex(a => a.id === x);
    res.push(data.slice(last,index));
    last = index;
  })
  return res.concat([data.slice(last)])
}

let result = split(data,"id3","id6")

const [first,second,third] = result;


console.log('First:',first);
console.log('Second:',second);
console.log('Third:',third);

If you want to do that on basis of id You can use findIndex and then slice()

3 Comments

@Urock Why don’t you iterate over the array and find the index of Id1 and id3 and then splice it?
It's not fixed response and it what if i add some objects between id1 and id2
@Andreas, I’m sorry I tagged you bymistkenly.
1

const data = [
    { name: 'name1', id: 'id1' },
    { name: 'name2', id: 'id2' },
    { name: 'name3', id: 'id3' },
    { name: 'name4', id: 'id4' },
    { name: 'name5', id: 'id5' },
    { name: 'name6', id: 'id6' },
    { name: 'name7', id: 'id7' },
    { name: 'name8', id: 'id8' },
];

const firstArr = [];
const secondArr = [];
const thirdArr = [];

data.map(item => {
    if (item.id < 'id3') {
        firstArr.push(item);
    } else if (item.id > 'id5') {
        thirdArr.push(item);
    } else {
        secondArr.push(item);
    }
});

console.log(firstArr);
console.log(secondArr);
console.log(thirdArr);

2 Comments

That is not what map is for. map is when you want to create a new array using the data from the original. In this case, you're splitting it into 3 new arrays, so you really should be using forEach instead.
Change id4 to id14 and test your solution.
1

You can use findIndex() to locate id3 and id6 and then use slice() and to extract the sub-arrays:

const data = [{name:"name1",id:"id1"},{name:"name2",id:"id2"},{name:"name3",id:"id3"},{name:"name4",id:"id4"},{name:"name5",id:"id5"},{name:"name6",id:"id6"},{name:"name7",id:"id7"},{name:"name8",id:"id8"}];

function process(arr) {
  const id3 = arr.findIndex(({ id }) => id === 'id3');
  const id6 = arr.findIndex(({ id }) => id === 'id6');
  return [arr.slice(0, id3), arr.slice(id3, id6), arr.slice(id6)];
}

const [arr1, arr2, arr3] = process(data);

console.log(JSON.stringify(arr1));
console.log(JSON.stringify(arr2));
console.log(JSON.stringify(arr3));

Comments

0

I'd use a reducer function like this

console.clear()
const data = [
  {name: "name1", id: "id1"},
  {name: "name2", id: "id2"},
  {name: "name3", id: "id3"},
  {name: "name4", id: "id4"},
  {name: "name5", id: "id5"},
  {name: "name6", id: "id6"},
  {name: "name7", id: "id7"},
  {name: "name8", id: "id8"}
];


// start and end are arrays, which contain triggers
// start will activate, end
// id is the key to check, defaults to 'id'
const reducerId = (activate, deactivate, key) => {
  key = key || 'id'
  let use = false
  return (item, index) => {
    if (activate.length === 0 && index === 0 || activate.includes(item[key])) {
      use = true
    }
    if (deactivate.includes(item[key])) {
      use = false
    }
    return use;
  }
}

// arr is the array to split
// use is a callback, which must return true or false, depending on whether the 
// currentItem should be used in the accumulated result array or not
const splitId = (arr, use) => {
  let found = false;
  return arr.reduce((accu, item, index, source) => {
    if (use(item, index)) {
      accu.push(item)
    }
    return accu
  }, [])
}


const first = splitId(data, reducerId([], ['id3']));
const second = splitId(data, reducerId(['id3'], ['id6']));
const third = splitId(data, reducerId(['id6'], []));
console.log(JSON.stringify(first))
console.log(JSON.stringify(second))
console.log(JSON.stringify(third))

Comments

0

You can use reduce

  • Here idea is first sort id's
  • Now loop through sorted data and as soon as you find any matching id push it to final output and remove that element from range and reset temp

const data = [{ name: 'name1', id: 'id1' },{ name: 'name2', id: 'id2' },{ name: 'name3', id: 'id3' },{ name: 'name4', id: 'id4' },{ name: 'name5', id: 'id5' },{ name: 'name6', id: 'id6' },{ name: 'name7', id: 'id7' },{ name: 'name8', id: 'id8' },];

let range = ['id3','id6','id9']
let temp = []
let op = data.sort(({id:a,id:b}) => a.localeCompare(b)).reduce((op,inp)=>{
  temp.push(inp)
  if(inp.id === range[0]){
    op.push(temp)
    temp = []
    range.shift()
  }
  return op
},[])
if(temp.length){
  op.push(temp)
}
console.log(op)

Comments

0

You could take an array for the id values and take a new array if you got a know id.

const
    data = [{ name: 'name1', id: 'id1' }, { name: 'name2', id: 'id2' }, { name: 'name3', id: 'id3' }, { name: 'name4', id: 'id4' }, { name: 'name5', id: 'id5' }, { name: 'name6', id: 'id6' }, { name: 'name7', id: 'id7' }, { name: 'name8', id: 'id8' }],
    groups = ['id3', 'id6'],
    [one, two, three] = data.reduce((r, o) => {
        if (o.id === groups[0]) {
            r.push([]);
            groups.shift();
        }
        r[r.length - 1].push(o);
        return r;
    }, [[]]);

console.log(one);
console.log(two);
console.log(three);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.